Reputation: 1671
I see the following bit operation statement, but what is the order of the execution:
// Example program
#include <iostream>
#include <string>
#include <stdio.h>
int main()
{
unsigned int age = 2;
unsigned int agemap = 0x111 ;
if(age > 0 && age <= 32)
{
agemap &= (unsigned int)~((unsigned int)1 << (unsigned int)(age - 1));
}
}
This is used to remove the age(value 2) from the agemap(0x111), but based on what order it is executed?
Upvotes: 0
Views: 67
Reputation: 41017
agemap &= (unsigned int)~((unsigned int)1 << (unsigned int)(age - 1));
If you remove (unnecesary) casts:
agemap &= ~(1U << (age - 1));
age - 1
1U << 1
~2
Upvotes: 1
Reputation: 399833
It's of course "based" on the order of precendence of C's operators, like in any other expression. There are plenty of parentheses of course, so you have to take those into account.
Wikipedia has a good table. Note that it's complicated since C has quite a few operators.
Basically, the right-hand side evaluates to ~(1 << 1)
, which is ~2
, which is 0xfffffffd assuming a 32-bit unsigned int
.
Upvotes: 1