0
if( condition && "Text in double quotes")
    {
    do this;
    }
else
    {
    do that;
    }

Saw this code in a program, in which case would the conditional expression in the IF-statement return true and in which case would it return false?

New Guy
  • 53
  • 6
  • non null string is always true, but false in `&&` condition always makes whole statement false – Iłya Bursov Sep 20 '22 at 04:56
  • I've seen similar code to 'add comments' to asserts, like this: `assert(condition && "Message");`. The string doesn't affect the result, but you will probably get the entire line with the message printed out if the assertion occurs. – prok_8 Sep 20 '22 at 05:31
  • See [How does C++ handle &&? (Short-circuit evaluation)](https://stackoverflow.com/questions/66680147/how-to-change-c-version-being-used-by-vscode) – Jason Sep 20 '22 at 05:45

1 Answers1

0

false && "Literally anything" is always false.
The primary expression is false, operator && is a logical operator (unless it was overloaded), so it will short-circuit.
This is because false && E (where E is an expression) is known to always evaluate to false. Therefore E doesn't need to be evaluated at all.
So if E was a function call with side effects: the side effects won't occur since the function is never called.

Example:

int main() { return false && "anything"; } // returns 0

Live on compiler explorer

viraltaco_
  • 814
  • 5
  • 14