0

So I'm looking up code in regards to 2D Haar Wavelet Transformation. And there's this if statement that I am confused about.

So part of the code looks like this:

unsigned char indexMask[4]; // the '4' here supposed to be a variable but I'm going to keep it simple here

for (int k = 0; k < 4; k++) {
indexMask[k] = 0;
}

for (int j = 1; j <= 5; j+=2) {
    if (indexMask[j/2]) {
        //some codes here
    }
}

My confusion is, what does the if statement here checks? This is my first time seeing a if statement structured this way so I sort of confused. Thanks alot

Hensley
  • 15
  • 4

3 Answers3

2

From cppreference (quoting only the relevent parts):

if ( condition ) statement-true

condition     -   expression which is contextually convertible to bool

In layman terms: Numbers can convert to bool. 0 is converted to false and everything else is converted to true.

Hence, the condition could also be written as

if (indexMask[j/2] != 0) {
    //some codes here
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
2

The expression indexMask[j / 2] is implicitly convertible to true or false. (It's an integral type, which will convert to false if 0 and true if any other value).

It's more readable than the hideous

if (indexMask[j / 2] == true) 

or other unnecessarily long variants. Note also that if the initialisation was

unsigned char indexMask[4] = {};

then you wouldn't need that loop to set the elements to 0.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

What happens here is that indexMask[j / 2] is contextually converted into a boolean value. So basically every int or char value that is not 0 will be contextually be converted into true, while 0 will be converted into false.

Note that this is how C programmers use conditionals, as C does not have a boolean type, they use integers to return true / false values instead.

Also note that the conversion is not implicit, but is rather a contextual conversion, there is a large difference between them. But I would rather not explain them as it is most likely not inside the scope of this question.

Famiu
  • 93
  • 7