Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange printf and puts statements explained

Tags:

c

printf

puts

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.

like image 355
laike9m Avatar asked May 01 '26 08:05

laike9m


1 Answers

" \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".

like image 76
R.. GitHub STOP HELPING ICE Avatar answered May 04 '26 01:05

R.. GitHub STOP HELPING ICE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!