Switch case expression

前端 未结 3 1751
栀梦
栀梦 2021-01-23 08:46

Consider an expression *(1+\"AB\" \"CD\"+1)

What is the solution for this expression ? The above expression is a switch expression in C.

*(2         


        
3条回答
  •  无人共我
    2021-01-23 09:15

    Here is a description of the different steps, all performed at compile time:

    • The sequence of string literals "AB" "CD" is concatenated at compile time into a single string literal "ABCD".
    • This string literal compiles to an array of 5 char, initialized with the values 'A', 'B', 'C', 'D' and '\0'.
    • In the expression 1 + "ABCD" + 1, the array decays into a pointer to its first element, said pointer is incremented by 2 to point to the third element, in this case the C byte.
    • Dereferencing this pointer evaluates to the char value 'C'.
    • The switch expression has a constant value 'C', converted to an int, although it is not a constant expression as defined by the C Standard.
    • The compiler will likely optimize the switch into a single call to printf with the string "Casabance", as can be verified on http://gcc.godbolt.org/#

    Note that the prototype for main in incorrect in your example, it should be int main(void) or int main(int argc, char *argv[]) or equivalent. Furthermore, it is error prone to omit the break; at the end of the last case or default clause in the switch block.

提交回复
热议问题