The unary operator "
!" (logical NOT) returns the negation of the argument. In other words, if you write the following:
bool flag = !true; //flag is false
bool flag = !false; //flag is true
So, when you have an
if
statement like this:
1 2 3 4 5
|
bool is_initialized = false;
if (!is_initialized) {
//...
}
|
The "
!" negates whatever
is_initialized
is. Since
is_initialized
is
false
at this point in time, the expression
(!is_initialized)
is equivalent to
(!false)
, which is
(true)
. For this reason, code execution enters the
if
branch.
why would it need to change the bool to true in the statement? |
This
if
statement sits inside of a loop, and it contains code that should be executed once and only once, since it's responsible for the initialization of something. Since we're in a loop, it could be that that "something" gets initialized more than once, which we don't want! The code in the if branch is only executed the first time it is evaluated, since
initialize
is initialized to
false
. In the
if
branch, the last thing we do is set
initialize
to
true
so that we'll never enter this
if
branch again in any of the following iterations of the loop.