-3

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_RENDERER_PRESENTVSYNC);
//                                                       ^ I have no idea what this means?

I don't know if this is a specific C++ feature?

My guess coming from shell scripting background suggests it could be a pipe (I know it's obviously not that), or it's just a bitwise OR?

What does a | mean when using it in a function parameter like the above code?

Holt
  • 36,600
  • 7
  • 92
  • 139
hoholee12
  • 334
  • 3
  • 14
  • 3
    See [bitwise logic operators](http://en.cppreference.com/w/cpp/language/operator_arithmetic#Bitwise_logic_operators). – songyuanyao Jun 14 '16 at 06:07
  • It's bitwise OR'ing operator. `01 | 10 = 11` – Arunmu Jun 14 '16 at 06:07
  • 1
    Very useful googlestring: "C++ operators". If you have a book, the operators are in the index. (You're going to want to look up more of them.) If you don't have a book, look [here](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) before you buy. – molbdnilo Jun 14 '16 at 06:10

2 Answers2

3

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.

Nicholas Betsworth
  • 1,707
  • 19
  • 24
0

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
Holt
  • 36,600
  • 7
  • 92
  • 139