Let’s see how good is your knowledge of the C language: ¿can you tell me what does the following snippet print?

    #include <stdio.h>

    int main(int argc, char **argv) {
        char *p = "hello";
        printf("%c\n", 2[p]); /* Attention here! */
        return 0;
    }

I know what the explanation is, if no one is able of telling why this snippets behaves the way it does, I will post the solution here in a week or so ;-)

P.S: I can guaranteee that it is a valid C program, and it even compiles passing -Wall and -pedantic to GCC.



12 Responses to “C language quiz”  

  1. mmm…
    *p is a array of chars, and if you print the second element of array it prints “l” because an array stat count in cero. Is it?

  2. You are right, it prints out “l”, but maybe you haven’t noticed this small difference: it is printing “2[p]” and not “p[2]”…

  3. 3 sagar

    actually there is no meaning of 2[p] in C as such……
    so compiler which ever it may be treat it as p[2] only……

  4. 4 Vijay

    It prints the ‘l’ . That is, the character can occupies the single Byte of Address. 2[p] is tells at the 2nd index of the address of the p[0] value.

  5. 5 aqwa

    It will print ‘l’. Because ‘2[p]‘ & ‘p[2]‘ having the same meaning in C.

  6. 6 baljeet

    answer is l

  7. 7 ravi

    there is an error in this program

  8. 8 Anonymous

    yes it is print p also .there is no problem in this program

  9. 9 khanna

    here p is the base address of character array.so the address of p[2] is evaluated as p+2 , which is equal to 2+p. so 2[p]
    gives same result as p[2]. that is ‘l’

  10. 10 mohit

    its l

  11. 11 nagarjuna

    In program it is declared that p is an array of characters.2[p] means p[2] which is “l” so it prints “l”only.


  1. 1 C language explanations « Hario no kai (はりおの階)

Leave a Reply