-2

I am having trouble understanding this piece of code where it is setting the value for vals[i].

for(int i = 0; i < 100; i++)
    vals[i] = (i%4==1)*255; 

Any help into understanding this would be greatly appreciated!

ADogg
  • 1
  • 2
  • 5
    Hint: A `bool` expression evaluates `false` as `0` and `true` as `1` when used in an arithmetic expression. Also take care about _operator precedence_ if you remove the parenthesis `()`. –  Feb 03 '18 at 14:36
  • Possible duplicate of [bool to int conversion](https://stackoverflow.com/questions/5369770/bool-to-int-conversion) – codebender Feb 03 '18 at 15:49

1 Answers1

0

Thank you to the the ones who left comments.

I concluded that this code

(i % 4 == 1) * 255

is pretty much an inline if without using the keyword.

Here are my testing notes in case it might help someone else.

int main()
{
    int size = 50;
    for (int i = 0; i < size; i++)
    {
        int val = i % 4 == 1 * 255;
        printf("%d) %d\n", i, val);
        // Output: Zero for every index
    }
    printf("\n--------------------\n");     // just for some spacing for readability
    for (int i = 0; i < size; i++)
    {
        int val = (i % 4 == 1) * 255;       
        printf("%d) %d\n", i, val);
        // Output...
        // 1) 255
        // 5) 255
        // 9) 255
        //...
    }
    printf("\n--------------------\n");     // just for some spacing for readability
    // This is a bit easier for me to understand, and it gives the same results as above
    for (int i = 0; i < size; i++)
    {
        int val = 0;
        if (i % 4 == 1)
            val = 255;
        printf("%d) %d\n", i, val);
        // Output...
        // 1) 255
        // 5) 255
        // 9) 255
        //...
    }
    return 0;
} 
ADogg
  • 1
  • 2