Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

constants

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?

like image 203
Rüppell's Vulture Avatar asked Apr 26 '13 11:04

Rüppell's Vulture


People also ask

Can we assign a value to constant variable in C?

In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization. In this section we will see how to change the value of some constant variables. If we want to change the value of constant variable, it will generate compile time error.

Can you declare a variable with const?

As a general rule, always declare a variable with const unless you know that the value will change. Use const when you declare: A new Array. A new Object.

Can you declare a constant with the keyword const?

The const keyword Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.

Can you reassign a constant?

The value of a constant cannot change through re-assignment, and a constant cannot be re-declared.


1 Answers

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.

like image 61
unwind Avatar answered Sep 21 '22 15:09

unwind