Why doesn't C support initializing constant variables with an if-else statement?

I want to initialize the const variable using if-else .
For instance:

 const int foo; if (bar) { foo = 1; } else { foo = 2; } 

In Java, this is legal code (using final instead of const ). The reason is that in all possible results, the variable is assigned once and never reassigned. In C, this is not a legal code. What is the reason that it cannot be legal code in C?

+5
source share
3 answers

You can use the ternary operator, but keep in mind that for objects with a static or thread-local storage class, the initializer expression must be a compile-time constant:

 const int bar = 42; #define BAR 42 #if 0 const int foo = bar ? 1 : 2; /*ERROR -- bar is not an integer constant */ #else const int foo = BAR ? 1 : 2; #endif void fn(void) { const int foo = bar ? 1 : 2; #if 0 static const int stc_foo = bar ? 1 : 2; /*ERROR*/ #else static const int stc_foo = BAR ? 1 : 2; #endif } 

The reason the if-else statement cannot be used for initialization is because it will require quite significant changes to the C grammar to resolve it, and this will probably complicate C's grammar and semantics significantly.

Basically, instead of just checking that the declarator is followed by the = and initializer expression, and that this initializer expression is constant, the compiler needs to remember every static / thread-local variable that has initialized, and then looks for unconditionally executable branches parsed during compilation, which follow its assignment to it and use them for initialization.

In addition, statements must be allowed in the file area (statements are not allowed in the file area in the current grammar C) and checked for restrictions on content capacity and memory that are limited to writing to translation unit global variables. Alternatively, they can be implicitly turned into global constructors, but this will lead to additional problems, such as arranging the constructor between compilation units (which would be difficult to resolve if the constructor generation was implicit), the need for implementations to support the global constructor in the first place or the blurring of currently quite simple performance characteristics of static variable assignments.

+6
source

You can initialize the variable foo conditionally with the ternary operator:

const int foo = bar ? 1 : 2;

Note that if foo not an automatic variable, then the initialization expression must be processed by abe at compile time, otherwise it will not compile.

+16
source

In C, const makes the variable read-only .

You can initialize the const variable only during declaration, and not after it, because it becomes read-only.

This is why your code is not legal in C, since you are updating a read-only variable .

Hope this helps!

+3
source

Source: https://habr.com/ru/post/1270628/


All Articles