How to access or modify the const variable in c ?
Answer Posted / gaurav bhandarkar
Author : Gaurav M. Bhandarkar
Yes u can modify constants...
Theory:
const int z = 420; // z is constant
&z (address of constant)
z (value of constant)
imp:
*(int*)((char*)&(*((char*)&z+1))-1) is
a unity/identity pointer operation resulting in z
That is:-
printf("%d | %d",*(int*)((char*)&(*((char*)&z+1))-1),z);
OUTPUT: 420 | 420
code:
const int z = 420;
printf("%d | %d\n",*(int*)((char*)&(*((char*)&z+1))-1),z);
//o-p 420 | 420
*((char *)&z+1) = 21; //corrupting the constant
printf("%d | %d",*(int*)((char*)&(*((char*)&z+1))-1),z);
//o-p 5540 | 420
___
The 2 similar printf's(check they are same)
o/p different values for same "z"
which is a constant!
thus the constant was corrupted!
| Is This Answer Correct ? | 53 Yes | 3 No |
Post New Answer View All Answers
Explain how do you generate random numbers in c?
If a five digit number is input through the keyboard, write a program to print a new number by adding one to each of its digits.For example if the number that is input is 12391 then the output should be displayed as 23402
Explain how do you declare an array that will hold more than 64kb of data?
Can you explain the four storage classes in C?
given post order,in order construct the corresponding binary tree
Explain what is wrong with this program statement? Void = 10;
Explain the difference between call by value and call by reference in c language?
How many levels of pointers have?
What are the different data types in C?
Explain main function in c?
How can I implement a delay, or time a users response, with sub-second resolution?
What happens if you free a pointer twice?
What are the 5 organizational structures?
Where is c used?
In C, What is the #line used for?