Search code examples
cprintf

Use of &ampersand and square bracket in printf


I came across the following code in an MCQ quiz,

#include <stdio.h>
int main()
{
    int j =2, k =4;
    printf(&j["Programming"], &k["Theory"]);
    k = j ^ 3;
    if (k == j)
        printf(&k["Practical"], "Trytosolve");
    else
        printf(&j["Problem creation"]);
    return 0;
}

where ampersand is used in the beginning itself and outside the quotes ("") of printf statement. I am only aware of the traditional use of printf statement and its format specifiers. I tried to run this code, and it showed no error but this warning: format not a string literal and no format arguments

and the following output

ogrammingoblem creation (this was one of the options in multiple choices)

I tried to search for such use, but could not find. Can someone explain this use of & and square brackets?


Solution

  • Say we have an array a and a variable i of integral type, then a[i] is equivalent to *(a + i), i.e. we can obtain the ith element of a by decaying a into a pointer to its first element, incrementing that pointer by i and dereferencing the result. This it true because arrays occupy contiguous addresses in memory.

    Now, as it turns out, i[a] is also equivalent to a[i], this is more of a "trick" that nobody (to my knowledge) would ever use in production. It's sort of intuitively justifiable that this would be the case because a[i] == *(a + i) == *(i + a) == i[a].

    So then, &j["Programming"] == &(*(j + "Programming")). And because dereferencing a pointer and then taking it's address is a noop, this is j + "Programming" == "Programming" + j == "ogramming", because strings are just arrays of characters.

    Same for the other branch, which is executed because 2 ^ 3 == 1 != 2.