user14399919
user14399919

Reputation:

Using a ternary operator inside of a preprocessor

I've just started learning C and I need some help with understanding macrocommands. I wanted to create one which calculates the maximum between two numbers.

I know the names are not chosen quite well, but it is just for testing purposes.

Here's the code:

#include <stdio.h>
#define max(a, b) (int max2, a>=b ? max2 = a : max2 = b)

void main()
{
    int a, b;
    scanf("%d%d", &a, &b);
    int maximum = max(a, b);
    printf("%d", maximum);
}

I'm getting an error on line 8, (the one with int maximum = max(a, b) ) saying "expected a ')'".

I guess that's because I'm using the preprocessor wrong (in my opinion), but I don't know how I should do it properly in this case.

Can anybody help me understand what am I doing wrong and how I should use preprocessors? Thanks.

photo

Upvotes: 1

Views: 2232

Answers (2)

Govind Parmar
Govind Parmar

Reputation: 21572

I don't think you understand how a macro works; you don't declare a new variable max2 inside it. The preprocessor is a simple text substitution system.

Your macro expands to:

int maximum = (int max2, a>=b ? max2 = a : max2 = b);

This is a syntax error. A max macro is very simple, all you need is:

#define max(a, b) ((a) >= (b)) ? (a) : (b)

This will then expand to:

int maximum = ((a) >= (b)) ? (a) : (b);

Which will give you the result you want.

Upvotes: 3

Dominique
Dominique

Reputation: 17565

What you have written, comes down to:

int maximum = (int max2, a>=b ? max2 = a : max2 = b); // this looks weird (what's that max2 for?)

Why don't you simply write the following:

#define max(a, b) ((a)>=(b) ? (a) : (b))

Like this, your line of code becomes:

int maximum = ((a)>=(b) ? (a) : (b));

Which looks a lot more logical. (Briefly, you don't need max2)

Upvotes: 3

Related Questions