Initialization of const from a function: What will be printed when const int x = get(); with get() returning 20 is executed and x is printed?

Difficulty: Easy

Correct Answer: 20

Explanation:


Introduction / Context:
Constants in C can be initialized with constant expressions or the results of function calls that are evaluated at runtime before first use. The const qualifier means the object cannot be modified after initialization, not that its initializer must be a compile-time literal. This problem clarifies that distinction by initializing a const int using a function that returns a known value and then printing it.


Given Data / Assumptions:

  • int get() { return 20; }
  • const int x = get();
  • printf("%d", x); is used to display the value.


Concept / Approach:

  • In C, function calls are valid initializers for automatic storage-duration variables, even if they are qualified const.
  • The qualifier const prevents subsequent modification through that identifier, but does not restrict the initializer to literals.
  • Since get() reliably returns 20, x is initialized to 20 and printing x yields 20.


Step-by-Step Solution:

Call get() during initialization → result 20.Bind result to x as a const int → x holds 20 and is read-only thereafter.printf("%d", x) → prints 20.


Verification / Alternative check:

If get() returned a different integer, that value would be printed; the presence of const does not change the initialization semantics.


Why Other Options Are Wrong:

  • Garbage value/0/implementation-defined: the value is clearly determined by get().
  • Error: there is nothing illegal about initializing a const with a function return value.


Common Pitfalls:

  • Confusing const with compile-time constant; in C (unlike some contexts in C++), const is not necessarily a constant expression.
  • Assuming that const implies static storage; it does not.


Final Answer:

20

More Questions from Constants

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion