switching int to perform binary operations?

Hello,

I have a function that returns an integer which I'd like to work using binary operations, but I CAN'T use any variables

the number represents walls around the object;
1 - right
2 - bot
4 - left
8 - top

so if there's a wall on right & left sides it will return 5, now is there a way to do something like this
1
2
3
4
5
6
7
8
9
switch(walls())
{
    case <switch here> & 1:
        //right
    case <switch here> & 2:
        //bot
    case <switch here> & 4:
        //left
}


without needing to call walls() more than 1 time? (the function actually moves the object around, so calling it several times wouldn't be efficient), please keep in mind I can't use any variables
Last edited on
> I can't use any variables
¿why not?
please keep in mind I can't use any variables
YOu are actually using one: switch(walls()) creates an anonymous variable which is used in switch expression.

Only way to do what you want is probably to enumerate all possibilities:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
constexpr int righ t = 1 << 0; //#define, use constants directly...
constexpr int bottom = 1 << 1; //Those are only for exposition here
constexpr int left   = 1 << 2;
constexpr int top    = 1 << 3;

switch(walls()) {
    case 0: //No walls
    case right: //Right
    case bottom: //bottom
    case right | bottom: //rigt and bottom
    case left:
    case right | left:
    //...9 more...
    case right | bottom | left | top:
    default:
}
Last edited on
Thought about the way to do that: http://coliru.stacked-crooked.com/a/640c1b2dec4b4edf NO VARIABLES

Edit: clang emits same code as mine for saving result in variable and several ifs:

http://goo.gl/oLBVwd
http://goo.gl/0KPJz6
Last edited on
@ne555 because professor said so
@MiiNiPaa well, I'm not sure I can use constants as well, and anonymous variable doesn't matter as long as it's returned by function or used in switch/if/while etc

yeah, I was thinking about doing some assembly as well, but that would take more time than taking totally different approach for this project :D but thanks anyway, I guess I have to do it other way
I'm not sure I can use constants as well
They are not nessesary, I just wanted to show what is done more clearly. I even added a comment that you can easily replace them with something else, even with integer literal directly.
Topic archived. No new replies allowed.