Q4. Discuss the role of assignment operator = in variable initialization and C++ shorthands. Support your answer with examples.
Ans. Any variable in C++ is initialized using an assignment statement. Variables can be declared in two manners:
- uninitialized variable
- initialized variable
An uninitialized variable is declared and initialize in separate statements. (Remember, a declaration is a statement that introduces a name to a program).
Some examples of uninitialized variables are as follows:
- int a; a=3;
- char ch; ch=’a’;
- float f1; f1=13.1239;
Here a separate assignment statement is required to initialize already declared variables.
An initialized variable combines its declaration and value assignment in a single statement.
int a = 13;
char ch = ‘a’;
float f1 = 13.1239;
Even in dynamic initialization of variables, assignment statement is part of the declaration.
float avg = sum/count;
Therefore, we can say that variables are initialized by means of assignment statements only.
C++ offers special shorthands that simplify the coding of a certain type of assignment statement.
a = a + 10;
can be written as
There operator pair + = tells the compiler to assign to a the value of a+10. This shorthand works for all the binary operators in C++ (those that require two operands). The general form of C++ shorthand is
var = var operator expression
is same as
var operator = expression
Following are some examples of C++ shorthands:
x-=10; equivalent to x = x – 10;
x*=3; equivalent to x = x * 3;
x/=2; equivalent to x = x / 2;
x%=z; equivalent to x = x % z;
thus, we can say =, *= , /=, %=, +=, -= are assignment operator in C++. The operators *= , /=, %=, += and -= are called arithmetic assignment operators. One important and useful thing about such arithmetic assignment operators of C++ is that they combine an arithmetic operator and an assignment operator, and eliminate the repeated operand thereby facilitate a condensed approach.