printf quirk

Hi,

Could anyone explain me the logic behind the following program's output?

int main() {
    printf("%d\n", printf("%d %d", 2, 2) & printf("%d %d", 2, 2));
    printf("%d\n", printf("%d %d\n", 2, 2) & printf("%d %d\n", 2, 2));
}

Ans:
2 22 23
2 2
2 2
4


printf("%d\n", printf("%d %d", 2, 2) & printf("%d %d", 2, 2));
3333333333333,11111111111111111111111,222222222222222222222,3

We start work or printf 3 but the integer argument involves two other functions and we must run those functions first to get the return codes. So printf number 1 runs and it prints "2 2" and it returns 3 (number of characters printed). The printf number 2 runs and does the same thing. So the current line looks like "2 22 2". 3 and 3 is 3. So printf number 3 prints a 3 and a newline producing the first line you show as output.

Same deal for the second line, but this time there are new line characters printed each time so we get a separate line for each printf. The new line character bumps the return codes up to 4.

2 Likes

nice i had same confuson too