-3

I have this code where I use "bitwise and" (&) to try and change x:

#include <stdio.h>

int main (void){

    unsigned long x = 0;
    printf("x = %lu\n", x);

    x &= 1;
    printf("x = %lu\n", x);

    return 0;

}

I compile and execute the code in order to get output:

x = 0
x = 0

But I expected:

x = 0
x = 1

Why?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
71GA
  • 1,132
  • 6
  • 36
  • 69

1 Answers1

3

It seems you mean the bitwise inclusive OR operator that can be used to set bits

x |= 1;
printf("x = %lu\n", x);

Or you could use another bitwise operator: the bitwise exclusive OR operator that can be used to toggle bits

x ^= 1;
printf("x = %lu\n", x);

Otherwise 0 & 1 will give 0 because initially x was initialized by 0

unsigned long x = 0;

Here is a demonstration program

#include <stdio.h>

int main( void )
{
    unsigned long x = 0;
    printf( "x = %lu\n", x );

    x |= 1;
    printf( "x = %lu\n", x );

    x = 0;
    x ^= 1;
    printf( "x = %lu\n", x );
}

The program output is

x = 0
x = 1
x = 1
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    This answer seems to imply that `x |= 1` and `x ^= 1` are interchangeable. It would be better to stress that `|=` *sets* a bit, while `^=` *toggles* the bit. – chepner Mar 08 '22 at 14:19