question mark at end of for loop

Oct 17, 2017 at 4:58pm
Hello everyone

i'm trying to figure out what is the use of the question mark (?) inside the brackets on the last assignment statement, i wonder if it's a typing error?

thanks for helping

1
2
3
4
int x = 0; 
for (int i = 0; i < 4; i++)
{
x += (i % 2 ? 1 : 0);
Last edited on Oct 17, 2017 at 5:20pm
Oct 17, 2017 at 5:18pm
See Conditional ternary operator
http://www.cplusplus.com/doc/tutorial/operators/

In the above example this
 
    x += (i % 2 ? 1 : 0);
amounts to the same as
1
2
3
4
    if (i % 2)
        x += 1
    else
        x += 0;

The expression i % 2 tests whether i is an odd number - if i is odd the remainder will be non-zero and the condition evaluates as logical true.

It seems a bit unnecessary, since x += 0; does nothing.

Compare these three versions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
using namespace std;

int main()
{
    {
        int x = 0;
        for (int i = 0; i < 4; i++)
        {
            x += (i % 2 ? 1 : 0); 
        }
        
        cout << "x = " << x << '\n';
    }

    {
        int x = 0;
        for (int i = 0; i < 4; i++)
        {
            if (i % 2)
                x += 1; 
        }
        
        cout << "x = " << x << '\n';
    }

    {
        int x = 0;
        for (int i = 0; i < 4; i++)
        {
            x += (i % 2); 
        }
        
        cout << "x = " << x << '\n';
    }

}

Topic archived. No new replies allowed.