#include<stdio.h>
int main()
{
switch(*(1+"AB" "CD"+1))
{
case 'A':printf("A is here");
break;
case 'B':printf("B is here");
break;
case 'C':printf("C is here");
break;
case 'D':printf("D is here");
break;
}
}
The output is: C is here.
Can anyone explain this to me its confusing me.
First of all, string literals only separated by white-space (and comments) are concatenated into single strings. This happens before expression parsing (see e.g. this translation phase reference for more information). This means that the expression *(1+"AB" "CD"+1)
is really parsed as *(1+"ABCD"+1)
.
The second thing to remember is that string literals like "ABCD"
are really read-only arrays, and as such one can use normal array-indexing with them, or letting them decay to pointers to their first element.
The third thing is that for any array or pointer p
and index i
, the expression *(p + i)
is equal to p[i]
. That means *(1+"ABCD"+1)
(which is really the same as *("ABCD"+2)
) is the same as "ABCD"[2]
. Which gives you the third character in the string. And the third character in the string is 'C'
.
In C, adjacent string literals, such as "AB" "CD"
, are concatenated. (This is a convenience that allows long strings to be easily broken up over multiple lines and enables certain features such as macros like PRIx64
in <inttypes.h>
to work.) The result is "ABCD"
.
A string literal is an array of characters. In most circumstances, an array is automatically converted to a pointer to its first element. (The exceptions are in contexts where you want the actual array, such as applying sizeof
.) So "ABCD"
becomes a pointer to the A
character.
When one is added to a pointer (to an element in an array), the result points to the next element in the array. So 1+"ABCD"
points to the B
. And 1+"ABCD"+1
points to the C
.
Then the *
operator produces the object the pointer points to, so *(1+"ABCD"+1)
is the C
character, whose value is C
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With