Why I got “operation may be undefined” in Statement Expression in C++?

后端 未结 1 471
别那么骄傲
别那么骄傲 2021-02-19 06:55

to describe the problem simply, please have a look at the code below:

int main()
{
    int a=123;
    ({if (a) a=0;});
    return 0;
}

I got th

相关标签:
1条回答
  • 2021-02-19 07:26

    According to the C++ grammar, expressions (apart from lambda expressions perhaps, but that's a different story) cannot contain statements - including block statements. Therefore, I would say your code is ill-formed, and if GCC compiles it, it means this is a (strange) compiler extension.

    You should consult the compiler's reference to figure out what semantics it is given (or not given, as the error message seems to suggest) to it.

    EDIT:

    As pointed out by Shafik Yaghmour in the comments, this appears to be a GNU extension. According to the documentation, the value of this "statement expression" is supposed to be the value of the last statement in the block, which should be an expression statement:

    The last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct. (If you use some other kind of statement last within the braces, the construct has type void, and thus effectively no value.)

    Since the block in your example does not contain an expression statement as the last statement, GCC does not know how to evaluate that "statement expression" (not to be confused with "expression statement" - that's what should appear last in a statement expression).

    To prevent GCC from complaining, therefore, you should do something like:

    ({if (a) a=0; a;});
    //            ^^
    

    But honestly, I do not understand why one would ever need this thing in C++.

    0 讨论(0)
提交回复
热议问题