"Const int x = get ();" legal in C? Can we assign the return value of a function to a constant when declared?

A senior contributor "R.."to this forum clearly told me about this 2 days ago:

Initializers for objects of static storage duration must be constant expressions. The result of a function call is not a constant expression.

He talked about global variables. But I'm not sure what happens to the constants declared inside the function main(), or any function in this regard. Although intuitively I feel that this is even for constants declared inside functions, the following program, obtained from the following link, with its supposedly answer correct, is confusing to 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 if this is really in C to assign the return value to a constant?

+5
3

, , , .. static.

static, .

, C " " , static, . static .

+7

, C. x , const, ( , C).

C11 (n1570), Β§ 6.6

, , , sizeof, , _Alignof  , .

42, 0L 89.0. , 2 , x .

const int x = 2;
+3

, , const static. , .

const , , , . , const. .

, . , static, , ( "" ), . , , , const.

- , C, ?

.

  • , , .
  • .
  • The return value of a function is not a constant expression.
  • Thus, a variable with a static storage duration cannot be initialized with the return value from the function.

As you can see, this had nothing to do with the keyword const, but everything related to where the variable was declared. If the variable, constor not, was declared inside the local scope, it would be nice to initialize it with any value, as shown in the code example.

+1
source

All Articles