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

后端 未结 2 1611
轮回少年
轮回少年 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 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.

提交回复
热议问题