+ 3

C++ output - Variable assignment

Code is: #include <iostream> using namespace std; int main() { int a = 7, b = 1; if(a = 8 || b == 5) cout << a * b; cout << " " << a; return 0; } In this case we have "8", but every and each value is assigned (please note single equal) to a in if, a "becomes" 1. Why?

7th Apr 2019, 6:50 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
2 Respostas
+ 3
|| has a higher precedence than =. a = 8 || b == 5 is the same as a = (8 || b == 5). (8 || b == 5) evaluates to true, or 1. Hence a = 8 || b == 5 will result in a being set to 1. if(a = 8 || b == 5) evaluates to true and the following line will be executed: cout << a * b; // same as cout 1 * 1; cout << " " << a; // cout << " " << 1.
7th Apr 2019, 8:09 AM
Anna
Anna - avatar
0
Я думаю что "а" присваивается значение "Boolean" равное "true", а "true" - это 1. I think that "a" is assigned the value of "Boolean" equal to "true", and "true" is 1.
7th Apr 2019, 7:12 AM
Solo
Solo - avatar