ProgrammingVery hardProduct company OA
What is the behavior?
What is the behavior?
const int x = 10;
int *p = (int*)&x;
*p = 20;
printf("%d", x);- A. Guaranteed to print 20
- B. Guaranteed to print 10
- C. Compilation error: cast from const int* is not allowed
- D. Undefined behavior: modifying an object originally declared const through a non-const pointer
Correct answer: D. Undefined behavior: modifying an object originally declared const through a non-const pointer
Casting away const-ness and writing through the resulting pointer is undefined behavior specifically because x was declared const; the compiler may have placed it in read-only memory (causing a crash) or may have assumed its value never changes and optimized reads of x elsewhere to a compile-time constant 10, regardless of the write.
More C Programming questions
- What is the behavior? c int a[3] = {1, 2, 3}; memcpy(a, a + 1, 2 sizeof(int)); printf("%d %d %d", a[0], a[1], a[2]);
- What is the behavior? c void f(int n) { char buf[n]; for (int i = 0; i <= n; i++) buf[i] = 'a'; } int main(void) { f(10); }
- What is printed? c // file1.c int x = 10; // file2.c (same program, separate translation unit) extern int x; void show(void) {…
- What is printed? c int x = 100; void f(void) { int x = 5; { int x = 1; printf("%d ", x); } printf("%d ", x); } int main(void) { f()…
- What is printed? c int x = 5; int f(void) { int x = x + 1; return x; } int main(void) { printf("%d", f()); }
- What is printed? c int f(void) { static int x; return x++; } int main(void) { printf("%d %d %d", f(), f(), f()); }