Martuza's blog

By Martuza, 12 years ago, In English

Sometimes we use flag variables for indicating some operations. and we need to change the value of flag 0 to 1 or 1 to 0. we use this statements

bool flag = 1;
if(flag == 1) flag = 0;
else flag = 1;

But how I get same result not using these statements? Have any mathematical calculation for this ? Please anyone help me.

  • Vote: I like it
  • -18
  • Vote: I do not like it

| Write comment?
»
12 years ago, # |
  Vote: I like it +16 Vote: I do not like it
bool new_flag = !flag;
int new_flag = 1 - flag;
»
12 years ago, # |
Rev. 2   Vote: I like it +14 Vote: I do not like it
bool flag = 1;
flag ^= 1

^ xor operation.

  • »
    »
    12 years ago, # ^ |
    Rev. 2   Vote: I like it -9 Vote: I do not like it

    Sorry I understand it.

    • »
      »
      »
      12 years ago, # ^ |
        Vote: I like it +1 Vote: I do not like it

      It will work anyway. Let's see an example. If flag is equal to true, then that line will work as flag = 1 ^ 1 = 0, else flag = 0 ^ 1 = 1.

    • »
      »
      »
      12 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      xor does exactly the same

»
12 years ago, # |
  Vote: I like it +1 Vote: I do not like it
bool flag = true;
flag = !flag;
»
12 years ago, # |
  Vote: I like it 0 Vote: I do not like it

flag ^= 1;