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

后端 未结 2 1613
轮回少年
轮回少年 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
    
    0 讨论(0)
  • 2021-01-29 16:02

    These are flags which you can set. In this instance | refers to the bitwise operator.

    In your example, this conveniently allows you to combine multiple flags through a single parameter.

    Suppose the two flags have the following values:

    SDL_RENDERER_SOFTWARE = 1 // Binary 0001
    SDL_RENDERER_ACCELERATED = 2 // Binary 0010
    SDL_RENDERER_PRESENTVSYNC = 4 // Binary 0100
    

    A logic bitwise OR of the two, would leave you with the value 6 for the flag. We can easily determine from this value which flags have been set using bitwise AND.:

    flag = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC // flag = 6 (0110)
    flag & SDL_RENDERER_SOFTWARE == 0 // Not set
    flag & SDL_RENDERER_ACCELERATED == 2 // Set
    flag & SDL_RENDERER_PRESENTVSYNC == 4 // Set
    

    Note that it's important here for the flags to be powers of two, to ensure all flag combinations result in a unique value.

    0 讨论(0)
提交回复
热议问题