Home > Mobile >  Change Value of Variable and return value using macros (c)
Change Value of Variable and return value using macros (c)

Time:12-22

I am trying to use macros to change the value of a variable but also return a value in the process.

Essentially I want to convert the following function into a macro

if (a%2){
    even = 1
} else {
  even = 0
}

return even

I am struggling to do both in one go; the compiler kept returning me errors each time (returning/changing value). Is there a way to do this using macros? Thank you so much! Note even is a variable already declared.

CodePudding user response:

Do this

return (even = (a % 2) ? 1 : 0);

You should use the ternary operator in these kinds of situations.

CodePudding user response:

A macro definition corresponding to the code shown in the question is:

#define MyMacro(even, a) ((even) = (a)%2 ? 1 : 0)

The ? : operator, used as E1 ? E2 : E3, selects its second (E2) or third (E3) operand according to whether the first operand (E1) evaluates as true (non-zero) or false (zero).

This macro produces an assignment expression, even = something. That “returns a value” as you request because an assignment expression can itself be used as a value. Its value is the value that is assigned.

Note that this macro sets even to be 1 if a is odd. If even is intended to describe the value of a, this contrasts with the sense of 1 versus 0 usually used. Normally, if a variable such as even is set to 1, it means something is even, and, if it is set to 0, it means the thing is not even. If you want to set even to 1 when a is even, you can use:

#define MyMacro(even, a) ((even) = (a)%2 ? 0 : 1)

That can also be written:

#define MyMacro(even, a) ((even) = !((a)%2)

because the ! operator produces 1 if its operand is 0 and 0 otherwise.

  •  Tags:  
  • c
  • Related