Whats the cout << i << " \n"[ i == n ] term doing?
Asked Answered
M

2

9

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.

Monofilament answered 14/12, 2017 at 3:41 Comment(3)
Possible duplicate of How can I get the nth character of a string?Nap
@underscore_d: Definitely not. Note the unusual expression in [ i==n ] .Reticulation
and through standard boolean evaluation, i == n becomes 0 or 1. So, once someone learns what "foo"[bar] does, "foo"[i == n] seems trivial to me.Nap
M
7

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

Manifesto answered 14/12, 2017 at 3:47 Comment(2)
Realy right use of the silly qualifier (It should be standardized)!Superabundant
Wonderful! Only, I would swap the arguments to [] for added quality. i["Hello World"]. ;-)Barbrabarbuda
P
15

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.

Prototype answered 14/12, 2017 at 3:45 Comment(1)
Never seen this before!Kraft
M
7

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

Manifesto answered 14/12, 2017 at 3:47 Comment(2)
Realy right use of the silly qualifier (It should be standardized)!Superabundant
Wonderful! Only, I would swap the arguments to [] for added quality. i["Hello World"]. ;-)Barbrabarbuda

© 2022 - 2024 — McMap. All rights reserved.