Question

I came across these two statements in a SNS photo album, with the title "the most elegant way of output I ever met" or something.

Here are the two statements:

printf("%d%c", a, " \n"[i==n]);
puts("YES\0No"+condition * 4);

I've no idea what they are doing and how they work. Will someone explain to me? Thank you.

Was it helpful?

Solution

" \n"[i==n] takes the expression i==n, which evaluates to either 0 or 1, and uses it as an index into the array " \n", obtaining either ' ' or '\n'.

"YES\0N0"+condition * 4 takes the array "YES\0N0", which 'decays' to a pointer to its first element when used in most expressions, including this one, and adds condition * 4 to this pointer. If condition is 1, that yields a pointer to the 'N' at the beginning of "N0".

OTHER TIPS

If i != n, a space is printed after %d, else a line-feed.

//  printf("%d%c", a, " \n"[i==n]);

// when i != n
printf("%d%c", a, " \n"[0]); // or
printf("%d%c", a, ' ');      // or
printf("%d ", a);      // or

// when i == n
printf("%d%c", a, " \n"[1]); // or
printf("%d%c", a, '\n');     // or
printf("%d\n", a);     // or

An interesting way to print a number separator, likely use in a for loop.

Similar for puts("YES\0N0"+condition * 4);

When condition is 0, it prints

puts("YES");`

When condition is 1, it prints

puts("N0");`  // Thanks @ Jonathan Leffler 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top