Tigran Iskandaryan
Tigran Iskandaryan

Reputation: 1451

My macro is not assignable

I'm trying to define a macro that returns an absolute value of numbers. Here how it looks like:

#define ABSOLUTE_VALUE(v) ( (v) < 0 ? (v) *= -1 : (v))

It works fine when I insert just a single number. The problem is, when I try to insert an expression (number + anotherNumber, for example), the compiler throws an error, saying that the expression is not assignable. I can't figure out why it does that. If you know the reason of the error, I would appreciate your help.

Upvotes: 1

Views: 159

Answers (2)

CRD
CRD

Reputation: 53000

From one of your comments:

The problem is that I'm trying to assign the result of (number + anotherNumber) * (-1) to an expression, which is number + anotherNumber. But shouldn't the + fire first, before the *= operator?

You are misunderstanding assignment. The left hand side (LHS) of an assignment must be an lvalue, which means something like a variable, which references a storage location into which values can be stored.

A value is just that, it is not associated with any storage location, you cannot assign to it. The result of your expression number + anotherNumber is a number, it cannot go on the LHS of an assignment.

Your macro would work if you simply replace =* with *.

HTH

Upvotes: 2

Davy M
Davy M

Reputation: 1696

What's going on here is that the entire expression number + anotherNumber is getting passed to your macro, so anywhere there is v, it's not the result v = number + anotherNumber, rather, v is replaced by number + anotherNumber before evaluation. So:

 (v) *= -1

Becomes

(number + anotherNumber) *= -1

Since number + anotherNumber is yet another number, that part of the code is trying to assign the value of -1 * (number + anotherNumber) to number + anotherNumber , which results in the error you are seeing, because you can't assign something to an expression.

Upvotes: 3

Related Questions