Single logical operator / SDL2 Question (No need to be familiar with SDL2)

Hi!..
*No need to be familiar with SDL2 but it would help to clarify some stuff.

I was going through an SDL2 guide and found a line of code where you can use
a single logical OR operator. So,
- what does it mean when you use only one logical operator?..
How does it affect the program?..
In what scenarios would one use logical operators this way? -

This is the line of code I'm talking about:

1
2
  main_renderer = SDL_CreateRenderer( main_window, -1, 
  SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);


Additional info:
The main_renderer part is just a variable that points to an SDL_Renderer type in SDL2.
- The first argument of the SDL_CreateRenderer() method is the window in which the renderer will be used.
-The second argument is what driver is going to be initialized
- Finally, the third argument is how will the renderer work basically.

Thanks for taking the time :^]
| is bitwise OR. Consider the following operation (binary (decimal)):
1100 (12) |
1010 (10) =
1110 (14)

It lines up the bits of the operands and performs OR bit-by-bit (bitwise). There's also bitwise AND, which uses AND instead of OR:
1100 (12) |
1010 (10) =
1000 (8)

The use of this in that snippet you posted, is that SDL_RENDERER_ACCELERATED has one value (say, 0x10), and SDL_RENDERER_PRESENTVSYNC has another value (say, 0x20). When you OR them, you're making a different value (0x30) that combines both values in such a way that SDL_CreateRenderer() can decompose.

Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int read(){
    int a, b, c;
    std::cout << "Enter three values (only 0 or 1 for each): ";
    std::cin >> a >> b >> c;
    return a | (b << 1) | (c << 2);
}

int main(){
    int n = read();
    int a = (n & 1) != 0;
    int b = (n & 2) != 0;
    int c = (n & 4) != 0;
    std::cout << "The values were: "
        << a << " "
        << b << " "
        << c << std::endl;
}
Notice how main() can decompose the single value into the original three values, despite never having seen them.
Oh, << is shift to the left. x << y is equivalent to x*(2^y) (x times 2 to the power of y). It "shifts" the bits of x to the left by y bits. It's analogous to how in decimal if you multiply by a power of 10 you shift all the digits to the left.
Last edited on
Topic archived. No new replies allowed.