Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

c - Why doesn't gcc allow a const int as a case expression?

I was looking at this SO question and got to thinking about const ints versus #defines and realized I don't actually understand why the compiler can't deal with this. Could someone shed some light as to why the following code

const int FOO = 10;

int main(int argc, char** argv)
{
    switch(argc)
    {
        case FOO: { printf("foo
"); }
        default:  { printf("default
"); }
    }
}

results in

error: case label does not reduce to an integer constant

I read the ISO-C99 spec which states in 6.8.4.2.3 that

The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion.

I understand why the case expression must be constant, but not why only a literal makes the compiler (gcc 4.2.1) happy.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A constant expression is not the same as a const-qualified type value, even though technically the value is known by the compiler at the point of the case statement.

Imagine what would happen if another file declared extern const int FOO and tried to use it the same way. The compiler wouldn't know what FOO was because it was defined in another file. Even though it has a constant value, it is not a constant expression.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...