Confusion with String Pointers

#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;
    }
}

Conclusion: C is here.

Can someone explain this to me that it confuses me.

+4
source share
3 answers

First of all, string literals, separated only by a space (and comments), are combined into single lines. This happens before parsing the expression (see, for example, this link to the transition phase for more information). This means that the expression is *(1+"AB" "CD"+1)really parsed as *(1+"ABCD"+1).

, , , , "ABCD", , .

-, p index i *(p + i) p[i]. , *(1+"ABCD"+1) ( , *("ABCD"+2)) "ABCD"[2]. . 'C'.

+11

C , "AB" "CD", . ( , , , PRIx64 <inttypes.h>.) : "ABCD".

- . . ( , , , sizeof.) , "ABCD" A.

( ), . , 1+"ABCD" B. 1+"ABCD"+1 C.

* , , *(1+"ABCD"+1) C, C.

+6

It switch(*(1+"AB" "CD"+1))is rated as switch(*(2+"ABCD")). * (2+"ABCD")indicates a symbol C. therefore the output of your code C is here.

*(any thing) evaluated as a pointer to a string literal.

+2
source

Source: https://habr.com/ru/post/1690390/


All Articles