set_bit want work

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

const int ERROR_BIT = 1 << 2;   // 0100

inline void set_error_bit(int flag){
  
  flag |= ERROR_BIT; // set ERROR_BIT
  return;
}


// test function for the bit
inline void 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);
}
flag in set_error_bit is a copy of the variable that you passed to the function. Modifying the copy will not affect the original variable.

If you want the function to be able to modify the argument that is passed to the function you will have to pass it by reference.

line 4: inline void set_error_bit(int& flag){
Hi...

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...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

const int ERROR_BIT = 1 << 2;   // 0100

inline void set_error_bit(int *flag){
  
  *flag |= ERROR_BIT; // set ERROR_BIT
  return;
}


// test function for the bit
inline void 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);
}
Thanks
Topic archived. No new replies allowed.