Search code examples
cboolean-expression

how does " for (int j = 0; j < n || !putchar('\n'); j++) " work


found this code that is responsible for printing out a two-dimensional array

for (int i = 0; i < n; i++)
 for (int j = 0; j < n || !putchar('\n'); j++)
  printf_s("%4d", A[i][j]); 

how does boolean expression that causes printing out an escape sequence at the end of each row work?


Solution

  • There are two things in play here:

    1. The short-circuit evaluation semantics of the logical AND and OR operators

    2. That !putchar('\n') will always be "false" (putchar returns either the character written or EOF, both are in this case non-zero and thus "true")

    While j < n is true then the right-hand side of || will not be evaluated because of the short-circuit semantics. When j < n is false then !putchar('\n') will be evaluated, and it will print a newline and return a "true" value (either '\n' or EOF on error) which due to ! becomes false so the whole condition becomes false and the loop ends.

    It's an obfuscated variant of

    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            printf_s("%4d", A[i][j]); 
        }
        putchar('\n');
    }
    

    I really recommend that you don't use (or worse, write) code as the one shown in the question. Obfuscation is not something to be proud of (unless you're entering into the IOCCC).