C constant expressions. const variables as constant expressions

Viewed 222

As per 6.6.10

10 An implementation may accept other forms of constant expressions.

the implementation may consider const (or even not const as answers are focused on it - but it is not the core of the question) variables as constant expressions.

Is my logic correct? If not why?

Some examples:

//file scope

int a = 5;
const int b = 10;

int c[a];
int d[b];

IMO both meet the requirements. They can be evaluated compile time. The value is known and the static arrays have sizes known compile time.

volatile int x = 5;  //cannot be considered as known compile time. ????
void foo(int a)
{
    static int b[a];
}

In this example a cannot be evaluated compile time - so it cannot be used as constant expression

2 Answers

Constant expressions doesn't have anything to do with the const qualifier. See 6.6/6 for the definition of an integer constant expression.

6.6/10 refers to the earlier parts of the same chapter speaking of integer constant expressions, constant expressions in initializers and so on. I believe the quoted part refers to various corner case expressions such as this:

static int x;
static int y = (int)&x;

This isn't strictly conforming since &x is not regarded as a integer constant expression but as an address constant. Neither gcc nor clang accepts it. I believe 6.6/10 allows compilers to support code like the above example as an implementation-defined extension.

Building on the link from @ryyker 's comment.

In C, an expression is considered constant if it's made entirely out of compile-time constants (i.e. literals). const variables are not accepted because const doesn't necessarily mean "constant"; it just means that a variable is immutable (read-only) from the perspective of the current compilation unit.

Consider a function like this one...

int add(const int a, const int b) {
    return a + b;

You could call this function by passing in compile-time constants, but you could also pass in mutable variables. If you pass in a variable, it is treated as const (read-only) for the purposes of that scope, but its value still isn't known at compile time so it isn't a "constant".

Related