iFreilicht
iFreilicht

Reputation: 14514

How to append to a C++ preprocessor macro?

A macro like M_PI is pretty useful, but it defines its value as a double. When using it as a float, you can't write M_PIf, because that obviously changes the name of the macro.

How can I append text to a macro?

Upvotes: 1

Views: 3203

Answers (4)

Mike Seymour
Mike Seymour

Reputation: 254691

You can't (at least not without involving more macros).

You can write float(M_PI), or static_cast<float>(M_PI) if you like verbosity.

Upvotes: 4

zmbq
zmbq

Reputation: 39029

You define another macro:

#define M_PI_F M_PI##f

Although (float)M_PI will be clearer to the reader.

Upvotes: 0

Bgie
Bgie

Reputation: 513

#define CONCATENATE_DETAIL(x, y) x##y
#define CONCATENATE(x, y) CONCATENATE_DETAIL(x, y)

CONCATENATE(M_PI,f)

This is more verbose than float(M_PI) and does not always work.

Upvotes: 3

Daniel Daranas
Daniel Daranas

Reputation: 22634

You can't. Each macro has an individual definition, and you can't just append an f to it. As an alternative, of course, you could always use a second macro which is the version which ends with an f.

But you shouldn't want to do it, anyway. Don't use macros to define numeric constants. Use constants. They're type safe, readable and efficient. They have everything you need and no drawbacks.

Upvotes: 2

Related Questions