In this statement
for (i = 1; i <= n; i++) {
cout << i << " \n"[ i == n ];
}
what is the last term in cout
statement [i==n]
doing?
This loop prints space separate numbers I guess.
It is an obtuse way of writing:
(i == n ? '\n' : ' ')
That is, when i == n
, a newline is printed, otherwise a space is printed.
The idea is to separate the numbers by spaces, and to put a newline after all the numbers have been printed.
It is a silly way to index either the character ' '
or the character '\n'
. This does the same idea and prints "Hello World":
#include <iostream>
int main() {
for (int i = 0; i < 11; i++)
std::cout << "Hello World"[i];
return 0;
}
i == n
is either going to be true
or false
. When cast to an integer for indexing using [i == n]
you get either the first or second element
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