We have used the assignment operator (=), which is often called equal to in algebra. On the left of this operator we write the name of variable or l-value to which a value is to be assigned, and on right side we write the value to be assigned to it or r-value. The l-value is the memory segment in which the r-value is stored. Let A, B, and ch is the names of three variables declared as given below.
int A ; // declaration allocates a memory space for A
A = 5; // assignment= stores value 5 in the memory
float B; // declaration allocates memory for B
B = 12.6; // store value 12.6 in the memory
char ch; // declaration allocates memory for ch
ch = 'H'; // Puts 'H' in the memory
We may as well combine the declaration and the assignment illustrated as follows.
int A =5;
float B =12.6;
char Ch = 'H';
In the assignment of ch, note that the character value 'H' is enclosed between single quotes (' '). Whenever the value is a character, it has to be enclosed between single quotes. On the other hand, if the value is a string of characters, it is enclosed in double quotes as illustrated below.
char Name - "Dinesh";
Here, Name is a string, i.e., it is an array of characters. Because of this reason we have used the array symbol [ ] with number 10 after Name. Number 10 indicates the number of characters in the string including the null character ('\0') which marks the end of the string. The null character is automatically appended by the system whenever the value assigned is enclosed in double quotes. We could also write the code as given below.
char Name  = "Dinesh";
char Name  = "Dinesh";
In the first case, the compiler will count the number of elements in the array and allocate appropriate memory space for it. In the second case, the system will allocate 12 bytes for the string (one byte for each character), out of which only 9 are occupied by the string Dinesh, the rest remain empty. C language also allows multiple assignment statements provided all variables are of the same type. For instance, we can write multiple assignments in the following manner:
float X,Y,Z,W; x = y = z = w = 4.5;
The associativity of = is from right to left. The above assignment expression is equivalent to the following expressions:
w = 4.5;
z = w;
y = z;
X = Y;
It is worthwhile to note that constant (0) zero is of type int but it can be assigned to variables of all data types.