What does putting a '|' on function parameter do?

后端 未结 2 1612
轮回少年
轮回少年 2021-01-29 15:19

I am learning how to write SDL program in C++, and I came across this code:

SDL_Renderer *ren = 
    SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_R         


        
2条回答
  •  一生所求
    2021-01-29 15:56

    The | is the bitwise OR operator, and in this case it is used to pass a set of flag to the SDL_CreateRenderer function.

    Imagine a set of flag:

    const int FLAG1 = 0x1 << 0; // 0b00...0001
    const int FLAG2 = 0x1 << 1; // 0b00...0010
    const int FLAG3 = 0x1 << 2; // 0b00...0100
    /* ... */
    

    As you can see from the binary representation of these flags, they only have one bit set to 1, and this bit is different for each flag, meaning that you can combine them using the | operator...

    int flag_a = FLAG1 | FLAG2; // 0b00...0011
    int flag_b = FLAG1 | FLAG3; // 0b00...0101
    

    ...while still being able to retrieve the original flags using the bitwise AND (&) operator:

    int is_flag1_set = flag_a & FLAG1; // 0b00...0001 != 0
    int is_flag2_set = flag_a & FLAG2; // 0b00...0010 != 0
    int is_flag3_set = flag_a & FLAG3; // 0b00...0000 == 0
    

提交回复
热议问题