What does C++ if-Statement with double parantheses do?

Viewed 262

I have stumbled upon an if statement where the condition is actually an assignment and I don't really understand what it does. Now, I found a similar Question with extensive answers but I still don't quite understand, what my snippet does:

if ((x = !x))
    /* some code */

The similar question I found is this one: https://unix.stackexchange.com/questions/306111/what-is-the-difference-between-the-bash-operators-vs-vs-vs

One user states, that

((…)) double parentheses surround an arithmetic instruction, that is, a computation on integers, with a syntax resembling other programming languages. This syntax is mostly used for assignments and in conditionals. This only exists in ksh/bash/zsh, not in plain sh.

What does that mean? Is the value of x toggled now and nothing else happened? In what case does this condition return false?

1 Answers

It does the same thing as if(x = !x) does. However, because it is very easy to accidentally use = in place of ==, compilers will warn you when you're using an assignment inside of an if statement. That warning doesn't get displayed if the assignment expression is inside of a second set of parenthesis.

So that's the point of the extra parens: to tell the compiler/reader that the writer really meant to use assignment rather than equality testing.

Related