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];
}
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" : " ";
}
The string literal " \n" is of type const char[3] (one for the 0-terminator) and you can access elements of that array as usual:
assert(" \n"[0] == ' ');
assert(" \n"[1] == '\n');
The "index" i == n-1 is true for all but the last iterations, which converts to 1 (while false becomes 0). So the same could have been written more readable:
for (int i = 0; i < n; i++) {
if ( i == n-1) {
cout << a[i] << '\n';
} else {
cout << a[i] << ' ';
}
}