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

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: D. Compile time errorConcept In C, placing const immediately after the * in a pointer declaration -- as in int *const p -- makes the POINTER itself a constant: once p is…

  1. A.

    It will print address of r

  2. B.

    It will print address of k and address of r

  3. C.

    It will print address of k

  4. D.

    Compile time error

Attempted by 2 students.

Show answer & explanation

Correct answer: D

Concept

In C, placing const immediately after the * in a pointer declaration -- as in int *const p -- makes the POINTER itself a constant: once p is initialized, the address it stores can never be changed by a later assignment. This differs from const int *p, where it is the pointed-to value (not the pointer) that is protected. A violation of either const rule is a constraint violation that every mainstream compiler (gcc, clang, MSVC) treats as a hard compile-time error, not something that surfaces while the program is running.

Application

  1. int k = 4; declares an ordinary int k.

  2. int *const p = &k; declares p as a constant pointer and initializes it to &k in the same statement -- that initialization is allowed, because a const object may be given its one and only value at the point of definition.

  3. int r = 3; declares an ordinary int r, unrelated to p so far.

  4. p = &r; now tries to store a new address in p after its initialization. Because p itself is const-qualified, the compiler treats this as writing to a read-only object and rejects it with an error such as 'assignment of read-only variable p'.

  5. Since this line fails to compile, the program never reaches printf("%d", p); -- there is no successful build to run, so no address is ever printed.

Cross-check

Contrast this with dropping const entirely: had p been declared as plain int *p = &k;, the line p = &r; would compile without complaint, and printf would then report the address of r. The const directly on p -- not on int -- is exactly what turns a legal pointer update into a compile-time error here.

Explore the full course: Gate Guidance By Sanchit Sir

Loading lesson…