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
What is a method in c?
What is the basic structure of c?
What is malloc and calloc?
How can I ensure that integer arithmetic doesnt overflow?
What is the purpose of clrscr () printf () and getch ()?
Why do we use c for the speed of light?
What is a floating point in c?
Where are local variables stored in c?
What is %d called in c?
What is the use of bit field?
What is the process to create increment and decrement stamen in c?
#define f(g,h) g##h main O int i=0 int var=100 ; print f ("%d"f(var,10));} wat would be the output??
What are structures and unions? State differencves between them.
Write a program to print factorial of given number using recursion?
Is c still used?