In this tutorial, you will get familiar with c programming variables and constants.
Actually variable is the location of a place in computer’s memory where the data is stored. To put it up simply, we can say a variable is a box in which we can store data.
Each variable is given a unique name called Identifier. So variables like num1
, num2
and others actually correspond to a location in computer memory.
For example:
int num1;
Here num1
is a variable of integer type.
It is called variable because it can hold different values at a different time.
For example, let’s suppose we assign value 3 to num1
then the memory location with name num1
will contain 3 and as soon we assign another value 5 to num1
the value at memory location num1
will be overwritten by 5.
Constants are the expressions with fixed values that do not change during the execution of the program. To put it up simply constant means whose value cannot be changed.
Following are the different types of constants we can use in C.
[adsense1]
Integer constants refer to the sequence of digits with no decimal points. The three kinds of integer constants are:
They are numeric constants with decimal points. The real constants are further categorized as:
Mantissa E exponent: where the Mantissa is either integer or real constant but the exponent is always in integer form.
For example, 12345.67 = 1.234567 E4, where E4 = 104.
Character constants are the set of alphabet enclosed in single quotes. For example: ‘A’, ‘f’, ‘i’ etc.
For example: ‘A’, ‘f’, ‘i’ etc…
As same as declaring a variable using the prefix const we can create new constants whose values can’t be altered once defined.
For example:
const int b = 100;
This signifies that b
will have a constant integer value of 100. Not only integer, by using prefix we can declare character constant and string constant as well.
String constants are the sequence of characters enclosed in a pair of double quotes (” “).
For example: “Hello”
Enumerated constant creates set of constants with a single line using keyword enum
.
Syntax
enum type_name{ var1, var2, var3 };
Here var1
, var2
and var3
are the values of enumerated datatype type_name
.
By default the var1
, var2
and var3
will have values 0, 1 and 2.
By using assignment operators, we can assign any value to var1
, var2
and var3
.
Visit C programming operators to learn about different operators used in C.
For example:
enum COLOR {RED = 5, GREEN, WHITE = 8};
This code sets red to 5 and white to 8.
The member without assigned value will possess the 1 higher value than the previous one. In this case, green will be set to 6.