C language quiz

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.


14 thoughts on “C language quiz

  1. 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……

  2. Pingback: C language explanations « Hario no kai (はりおの階)

  3. 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.

  4. 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’

  5. 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s