New course! Every coder should learn Generative AI!
Try a free lesson0
In c++ what use is there for &&
?
3 Answers
+ 5
It is the logical operator "and". So, if I were to say...
int x = 5;
int y = 9;
if (x > 6 && y == 9)
{
cout << "That is true!" << endl;
}
else
{
cout << "This is the answer! I will be printed." << endl;
}
The else statement would be executed.
+ 1
Also keep in mind,
&& will stop evaluating the conditions as soon as one of them is false.
(Meanwhile, & will always evaluate both conditions.)
Example/
int a = 4;
if(++a < 5 && ++a == 6)
a += 10;
cout << a;
Output: 5
(If I put & the output would be 6).
0
Just complementing the other posts, it might also be used for rvalue references, necessary for move semantics. In short, it adds some efficiency to some situations by moving values insteading of copying.