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 Dynamic memory allocation in C? Name the dynamic allocation functions.
What are qualifiers?
Can you explain what keyboard debouncing is, and where and why we us it? please give some examples
What is modeling?
What are control structures? What are the different types?
List the difference between a "copy constructor" and a "assignment operator"?
What is the use of printf() and scanf() functions?
what is stack , heap ,code segment,and data segment
What is boolean in c?
Device an algorithm for weiler-atherton polygon clipping, where the clipping window can be any specified polygon
Write a C program to help a HiFi’s Restaurant automate its breakfast billing system. Your assignment should implement the following items: a. Show the customer the different breakfast items offered by the HiFi’s Restaurant. b. Allow the customer to select more than one item from the menu. c. Calculate and print the bill to the customer. d. Produce a report to present your complete program and show more sample output. Assume that the HiFi’s Restaurant offers the following breakfast menu: Plain Egg $2.50 Bacon and Egg $3.45 Muffin $2.20 French Toast $2.95 Fruit Basket $3.45 Cereal $0.70 Coffee $1.50 Tea $1.80
What is static memory allocation? Explain
An instruction which is analysed and acted upon by the processor prior to the compiler going its work a) directive b) constructive c) constant d) absolute mode
What is the role of && operator in a program code?
console I/O functions means a) the I/O operations done on disk b) the I/O operations done in all parts c) the input given through keyboard is displayed VDU screen d) none of the above