Consider an expression *(1+\"AB\" \"CD\"+1)
What is the solution for this expression ? The above expression is a switch expression in C.
*(2
Running your code you'll get answer "Casabance"
"AB" "CD"
is equal to "ABCD"
*("ABCD")
points to 'A'
*("ABCD" + 0)
points to 'A'
*("ABCD" + 1)
points to 'B'
*("ABCD" + 2)
points to 'C'
'C'
answer is "Casabance"Casabance.
If you have
char *cp;
int i;
then cp[i] == *(cp+i) == *(i+cp) == i[cp]
.
C11 6.5.2.1:
A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))).
And C11 6.5.6:
When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression.
A string literal is just a char pointer as far as the compiler is concerned.
Two string literals next to each other auto concatenate into a single string literal:
C11 6.4.5:
In translation phase 6, the multibyte character sequences specified by any sequence of adjacent character and identically-prefixed string literal tokens are concatenated into a single multibyte character sequence.
So... *(1+"AB" "CD"+1) == *(1+"ABCD"+1) == *("ABCD"+1+1)==*("BCD"+1) == "BCD"[1] == 'C'
.
Here is a description of the different steps, all performed at compile time:
"AB" "CD"
is concatenated at compile time into a single string literal "ABCD"
.char
, initialized with the values 'A'
, 'B'
, 'C'
, 'D'
and '\0'
.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.char
value 'C'
.'C'
, converted to an int
, although it is not a constant expression as defined by the C Standard.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.