Hello.
I try to set a bit in a constant variable.
My inline function want set the bit. If I do the same in my "main" function the code works.
What is my error?
constint ERROR_BIT = 1 << 2; // 0100
inlinevoid set_error_bit(int flag){
flag |= ERROR_BIT; // set ERROR_BIT
return;
}
// test function for the bit
inlinevoid test_error_bit(int flag){
if ((flag & ERROR_BIT) != 0){
cerr << " Error flag is set: \n";
}
else
cerr << " No error detected: \n";
return;
}
int main(){
int flag = 0;
// set_error_bit(flag); // this want work
flag |= ERROR_BIT; // this way it works
test_error_bit(flag);
return(0);
}
You are calling set_error_bit function as call by value so even you set the bit in that function it will not effect in main function... call the function with call by reference then your code will work...
constint ERROR_BIT = 1 << 2; // 0100
inlinevoid set_error_bit(int *flag){
*flag |= ERROR_BIT; // set ERROR_BIT
return;
}
// test function for the bit
inlinevoid test_error_bit(int flag){
if ((flag & ERROR_BIT) != 0){
cerr << " Error flag is set: \n";
}
else
cerr << " No error detected: \n";
return;
}
int main(){
int flag = 0;
set_error_bit(&flag); // this way it works
/* flag |= ERROR_BIT; // this way it works */
test_error_bit(flag);
return(0);
}