Strange printf commands and explanations

I met these two statements in the SNS photo album, titled "the most elegant output method I've ever come across" or something like that.

Here are two statements:

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

I have no idea what they do and how they work. Anyone explain to me? Thank.

+3
source share
2 answers

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

"YES\0N0"+condition * 4 "YES\0N0", "" , , , condition * 4. condition 1, 'N' "N0".

+6

i != n, %d , -.

//  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

, , for.

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

0,

puts("YES");`

1,

puts("N0");`  // Thanks @ Jonathan Leffler 
+1

All Articles