I just found this "C++" today and i cannot make sense of it:
if(array[i][j]) {--i;--j;}
can anyone explains to me how this work? I just don't get it. What is the condition here? It seems like it would be true every time, but when i got rid of the IF (so only this {--i;--j;}
left.) it doesn't work the same.
I'm quite new to C++ so go easy with the explanations! :)
Thanks!
If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed. On the other hand if you need a code to execute “A” when true and “B” when false, then you can use the if / else statement.
C - General Programming - Return value of a if statement without any condition. To test a condition in a if statement without any condition, the result has to be other than 0 to test a true condition. Result: $ True - Value was -1.
else can be omitted for any if statement, there is nothing special in the last if of an if / else if chain.
Yes, else statement can exist without an if statement.
In C++, a non-zero value can be used to indicate 'success' in a conditional statement.
This is from C99, section 6.8.4.1:
The
if
Statement2 In both forms, the first substatement is executed if the expression compares unequal to 0.
From C++03, section 6.4
4 The value of a condition that is an initialized declaration in a statement other than a switch statement is the value of the declared variable implicitly converted to type bool. If that conversion is ill-formed, the program is ill-formed. The value of a condition that is an initialized declaration in a switch statement is the value of the declared variable if it has integral or enumeration type, or of that variable implicitly con- verted to integral or enumeration type otherwise. The value of a condition that is an expression is the value of the expression, implicitly converted to bool for statements other than switch; if that conversion is ill-formed, the program is ill-formed. The value of the condition will be referred to as simply “the condi- tion” where the usage is unambiguous.
And boolean conversion is defined in 6.3.1.2
6.3.1.2 Boolean type
1 When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.
And int
is a scalar type. I assume that's what your array is filled with as you can use unary ++
and --
on them.
assuming array is an array of int (or other integral types) the condition will be false if and only if array[i][j] == 0
The if
is gets a true
if array[i][j]
gets true
when cast to a bool
. If array
has e.g. float
or int
values, anything not equal to 0
will be cast to true
. The situation could be different for user-defined types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With