I didn't get how [i == n-1] works in this scenario
for (int i = 0; i < n; i++) {
cout << a[i] << " \n"[i == n - 1];
}
Expression i == n-1 is a boolean expression that will evaluate to either 1 (True) or 0 (False).
" \n" is an array of 3 character values:
Space (0x32)\n (0x0D)NULL (0x00)So the full expression will either evaluate to the Space or the \n, depending on if i is the last index of array a.
The complete for-loop with cout will print spaces up until i is at the end of the array, and then will finally print a \n after the last element.
It is clever, but confusing. I would tell a programmer to find a better way.
I might prefer using a ternary operator (? :)
for (int i = 0; i < n; i++) {
cout << a[i] << (i == n - 1) ? "\n" : " ";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With