Is "const int x = get();" legal in C?Can we assign a function's return value to a constant at declaration?

c, constants

Solution

Yes, it's perfectly valid, since your variable is automatic, i.e. not `static`.

The restrictions apply to `static` variables, whose values must be known at compile-time.

Note that C differentiates between "constant expressions" and other expressions, and that the initializer value used for `static` variables must be such a constant expression. For non-`static` variables, there is no such requirement.

Problem

A highly reputed contributor `"R.."` on this forum explicitly told me this 2 days back: `Initializers for objects of static storage duration must be constant expressions. The result of a function call is not a constant expression.` He was talking about global variables.But I am not sure what goes with constants declared inside the `main()` function, or any function for that matter.Though intuitively I feel it is so even for constants declared within functions,the following program sourced from the following link, with its supposedly `correct` answer, is confusing me. http://www.indiabix.com/c-programming/const/discussion-546 ``` #include<stdio.h> int get(); int main() { const int x = get(); printf("%d", x); return 0; } int get() { return 20; } ``` So can anyone explain whether it's valid in C to assign a return value to a constant?

Original source