|| operator question

I don't quite understand the output, which is 1.
At the line, i=fun(1) || fun(2); , why does i equal to 1?
fun(1) returns 2
fun(2) returns 4
can someone explain the step by step process of the code? please help

1
2
3
4
5
6
7
8
9
10
11
12
13
  #include <iostream>

using namespace std;
int fun(int x) {
    return 2*x;
}

int main() {
    int i;
    i = fun(1)||fun(2);
    cout << i;
	return 0;
}
when you use the || operator, also known as 'or', it will always return 0 for false or 1 for true.
in this case:

i = fun(1)||fun(2);

fun(1) returns 2 || fun(2) returns 4

2 || 4
you can also consider that numbers different from 0 are considered true as well.
so you can that 2 || 4 becomes:
1 || 1

the truth table for '||' is
1
2
3
4
5
a   b    a || b
1   1       1
1   0       1
0   1       1
0   0       0


so 1 || 1 returns: 1 and 1 is assigned to i;


sorry if I couldn't explain very well
Last edited on
you can also consider that numbers different from 0 are considered true as well.
^that was it. Thank you Krugle.
you're welcome
Topic archived. No new replies allowed.