Search code examples
cembeddedavr

What is the difference between = and |= in C?


I'm new to C and I am trying to understand the difference between

DDRB |= 0b00000001;    

and

DDRB = 0b00000001;    

Do the two lines have same effect of writing one to data register B ?

How are they different?

Just could register google search for "|" ..so needed some help in understanding it.


Solution

  • Do the two lines have same effect of writing one to data register B ?

    No.

    DDRB = 0b00000001;   
    

    writes one to bit-0 and zero to bits 1 to 7, while:

    DDRB |= 0b00000001;   
    

    is a read-modify-write operation equivalent to:

    DDRB = DDRB | 0b00000001;   
    

    so it writes a one to bit-0 as before and leaves all other bits unchanged.

    So for example if DDRB's current value were 0b11110000 after:

    DDRB = 0b00000001;   
    

    it will be 0b00000001 while after:

    DDRB |= 0b00000001;   
    

    it will be 0b11110001.

    So one sets DDRB to 1, while the other sets DDRB:Bit-0 to 1.