What will be the output of the following C code? #include <stdio.h> void…

2026

What will be the output of the following C code?
#include <stdio.h>
void main()
{
int k = 4;
int *const p = &k;
int r = 3;
p = &r;
printf("%d", p);
}

Answer: C. Compile time errorConcept: In C, the position of const relative to * decides what is immutable. Writing int *const p makes the pointer variable p itself read-only after…

  1. A.

    Address of k

  2. B.

    Address of r

  3. C.

    Compile time error

  4. D.

    Address of k + address of r

Attempted by 4 students.

Show answer & explanation

Correct answer: C

Concept: In C, the position of const relative to * decides what is immutable. Writing int *const p makes the pointer variable p itself read-only after initialization, while const int *p (or int const *p) makes only the value it points to read-only. Once a pointer is declared as int *const, any later attempt to assign it a new address is rejected by the compiler, because a const object can only be initialized once, at its declaration, and never reassigned afterward.

Step-by-step walkthrough:

  1. int k = 4; declares an integer variable k and initializes it to 4.

  2. int *const p = &k; declares p as a constant pointer to int, initialized to hold the address of k. From this point onward, the address stored in p itself can never change.

  3. int r = 3; declares a second integer variable r and initializes it to 3.

  4. p = &r; attempts to store the address of r into p. Because p is a constant pointer, this reassignment violates its read-only nature.

  5. The compiler therefore stops at this line with an error rather than producing an executable, so the printf("%d", p); statement is never reached and the program never runs.

What the compiler actually reports for this code:

$ cc pgm11.c
pgm11.c: In function 'main':
pgm11.c:7: error: assignment of read-only variable 'p'
pgm11.c:8: warning: format '%d' expects type 'int', but argument 2 has type 'int * const'

Line 7 (counting the #include line as line 1) is exactly p = &r;, and the fatal error there is what stops compilation. The line-8 message is only a warning, not the reason compilation fails -- and separately, even the source code's own printf("%d", p) mixes a pointer argument with the %d specifier meant for a plain int, which is itself undefined behavior in C; that mismatch never gets exercised here anyway because the program never compiles.

Cross-check: If the declaration had instead been const int *p = &k; (or int const *p = &k;) -- a pointer to a constant int -- then p = &r; would be perfectly legal, because that const binds to the pointee (*p), not to the pointer p itself; only modifying *p would fail. It is the *const placed directly after the * that fixes p in place here, so the correct outcome for this exact declaration is a compile-time error, not a printed address.

Explore the full course: Gate Guidance By Sanchit Sir

Loading lesson…