why does the 2nd statement creates Assigning to non-lvalue '' main.c?

257 Views Asked by At

hi whats the difference between these statements given below?

 #define RES_WRITE 0Xf0f0
 #define DATA (0x0000 |= (1<<15))
 #define DATA (RES_WRITE |= (1<<15))

when DATA is assigned to a int variable it shows an error like "Assigning to non-lvalue. may i know the reason behind this error and how to resolve the error what mistake i am doing?

2

There are 2 best solutions below

1
SpongeBob On BEST ANSWER

I think you want to send 0b1000000000000000 to a port of a microcontroller or globally to a buffer. change |= to |

why you faced error?

consider one of your macros:

#define DATA (0x0000 |= (1<<15))

in this macro, you try to do this:

0x0000 = 0x0000 | (1<<15))

is it possible to write data on 0x0000? 0x0000 is value; it means that it don't have any location on memory.

1
Lukas-T On

x |= y is the shorthand for x = x | y, so you end up with

0 = 0 | (1 << 15)

In this expression you are trying to assign something to a literal, which is not possible. Also the | is redundant, since 0 | x is always just x.

From your comment "i want to mask diffent bits and then assign all the bits to one variale" it seems like you want simple constants that mask a single bit:

#define DATA (1 << 15)

which is a integral number with only 1 bit set, that can be used as a mask. For various reasons you should prefer constexpr over macros in modern C++:

constexpr unsigned DATA = 1 << 15;

You can use both like you mentioned

auto x = DATA | 0x00f0 | 0x0100;