Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - switch case: error: case label does not reduce to an integer constant

int value;

const int signalmin = some_function();

switch(value)
{
   case signalmin:
   break;
}

I read the value of some_function and use that int value to do a switch case on. The C99 compiler gives back:

error: case label does not reduce to an integer constant

But I cannot use a #define because the int value is being read before the switch executes.

question from:https://stackoverflow.com/questions/14069737/switch-case-error-case-label-does-not-reduce-to-an-integer-constant

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

1 Reply

0 votes
by (71.8m points)

switch labels must be constant expressions, they have to be evaluated at compile time. If you want to branch on run-time values, you must use an if.

A const-qualified variable is not a constant expression, it is merely a value you are not allowed to modify.

The form of integer constant expressions is detailed in 6.6 (6) [C99 and the n1570 draft of the C2011 standard]:

6 An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, _Alignof expressions, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof or _Alignof operator.

The restriction that only sizeof expressions whose result is an integer constant are allowed rules out sizeof expressions whose operand is a variable length array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...