function multiple enum inputes

Started by
19 comments, last by moeron 19 years, 6 months ago
when using an enumeration in a function, how can you make it so it has multipe inputes with |, like in SDL_init(SDL_Init_Video|SDL_Init_Audio)?
Advertisement
Make the numeric values correspond to an individual bit, you can test for that bit being set, and hence for that flag inside the function.
can i get an example?
Well, for example

int flag1 = 1; //01
int flag2 = 2; //10
int flag3 = 4; //100

int flags = flag1 | flag2 | flag3; //111

void func(int flags){
if(flags & flag1) //only true if bit 1 is set for both ints
...
if(flags & flag2) //only true if bit 2 is set
..etc

}
so flags holds multiple intigers? y do u need to say (flags & flag1)? y do they both need to be true?
if(flags & flag1) evaluates to true if the flag1 bit was set. For instance:

flags = flag2 | flag3; // flag 1 not set so flags is 110 not 111

if(flags & flags1) // false because 110 & 001 is false
Quote:Original post by Yamian
so flags holds multiple intigers? y do u need to say (flags & flag1)? y do they both need to be true?


The single & is a bitwise AND. Only the bits that are set in both operands are kept.
12 & 8 = 8 . binary: 1100 & 1000 = 1000
8 & 8 = 8 . binary: 1000 & 1000 = 1000
12 & 4 = 4 . binary: 1100 & 0100 = 0100
8 & 4 = 0 . binary: 1000 & 0100 = 0000

So by choosing values for the flags that have only a single bit set, you can combine them using | (bitwise OR) and find out which ones are set using & (bitwise AND).
but what does just 'flags' return if it seperate from 'flag1' visa-versa?
Check out this tutorial, Yamian.
hm, not sure if i understood that question. I guess you want to know what value is stored in flags?

int flag1 = 1; // binary: 0001int flag2 = 2; // binary: 0010int flag3 = 4; // binary: 0100int flags1 = flag1 | flag2;int flags2 = flag1 | flag3;int flags3 = flag2 | flag3;


flags1 will be 3 (binary: 0011)
flags2 will be 5 (binary: 0101)
flags3 will be 6 (binary: 0110)

The actual value doesn't matter that much, you check if a flag is set using bitwise AND.

This topic is closed to new replies.

Advertisement