Home > Enterprise >  Using #define for text replacement in the code
Using #define for text replacement in the code

Time:10-02

Apparently, I can set

#define LIMIT 50

to say that LIMIT, wherever it occurs in the code, is replaced by 50.

Is it possible to use

#define ui "unsigned int"

to define my variables in such a way?

ui foo = 42
ui bar = 99

CodePudding user response:

Using the preprocessor for replacement is not recommended and can lead to unexpected problems.

For your use-case there is the typedef or using statement:

Use:

using ui = unsigned int;

Or:

typedef unsigned int ui;

CodePudding user response:

There are two problems with

#define ui "unsigned int"

The first is that the macro replacement is a string and not a type.

The second is that such macros (and even type-aliases) tend to make the code harder to read, understand and maintain.

CodePudding user response:

MACRO just does text replacement, so with:

#define ui "unsigned int"
ui foo = 42;
ui bar = 99;

you got, after substitution


"unsigned int" foo = 42;
"unsigned int" bar = 99;

which is invalid.

Syntax would be:

#define ui unsigned int

But better to use typedef here (so scope and type are respected):

old school:

typedef unsigned int ui;

modern way:

using ui = unsigned int;
  • Related