Loading....
Coupon Accepted Successfully!

 

const Arguments

The constant variable can be declared using const keyword. The const keyword makes variable value stable. The constant variable should be initialized while declaring.
 

Syntax:

(a) const <variable name> = <value>;

(b) <function name> (const <type>*<variable name>;)

(c) int const x // invalid

(d) int const x =5 // valid


In statement (a), the const modifier enables to assign an initial value to a variable that cannot be changed later by the program.

 

For example,

const age = 40;


Any attempt to change the contents of const variable age will produce a compiler error. Using pointer one can indirectly modify a const variable as per the following:

 

*(int *)&age = 45;


When the const variable is used with a pointer argument in a function’s parameter list, the function cannot modify the variable that the pointer points to. For example,

int cube(const int *x, ...);


Here the cube function is prohibited from altering the integer variable.


7.13 Write a program to declare constant variable.

Explanation: In the above program, the prototype of function min() declares two arguments. Out of two arguments the first argument a is constant and its default value is 8. The second variable is b and default value is 20. In function main() we can change the value of variable a, because in main() it is not declared as a constant. When function min() is invoked, the first argument j is a constant according to prototype of function. Any attempt made to change the value of variable j will cause an error message “cannot modify a constant variable.”


7.14 Write a program to change the value of a constant variable using pointer.

 

 

Explanation: In the above program, the variable x is a constant integer variable. In C it is possible to change the value of a constant variable using scanf() statement, that is run time assignment. In C++, though compiler accepts this statement, the value is not changed. We can change the value of constant variable using a pointer. The statement ++(*(int *)&x); points to the address of the variable x and increase is done in the value stored at the location, that is indirectly to variable x. Though it is possible to change the value of a variable using pointer, the following statements are invalid.


It is not possible to change the value of a variable using pointer *p. From the above program we learned that the value of a constant could be changed using pointer.





Test Your Skills Now!
Take a Quiz now
Reviewer Name