Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does cout << " \n"[i == n - 1]; work?

Tags:

c++

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];
}
like image 317
Fabbiucciello Avatar asked Oct 24 '25 21:10

Fabbiucciello


1 Answers

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" : " ";
  }
like image 132
abelenky Avatar answered Oct 26 '25 12:10

abelenky



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!