D
D
DredWolf2020-04-28 20:45:11
C++ / C#
DredWolf, 2020-04-28 20:45:11

Do C++ preprocessor directives have scope?

Does it make sense to move all directives to the global code area, to the beginning, or is it necessary to write each directive separately for functions?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Zhilin, 2020-04-28
@DredWolf

No, preprocessor directives are not limited to any scopes. They replace absolutely all occurrences of the corresponding name after their definition. Example:

namespace what {
#define apples 2
}

namespace stuff {
    class foo {
    private:
        int apples = 3;  // ОШИБКА: 2 - недопустимое имя
    public:
        int read_apples() {
            return apples;  // 2
        }
    };
}

Moral: don't use macros where you can get by with constexprconstants or inlinefunctions. And where they are needed, give them long scary SCREAMING_NAMES.

A
Armenian Radio, 2020-04-28
@gbg

Directives do not have scopes, but they do have #undef
Read about the X-MACRO approach
However, you need to understand that in C++, using a preprocessor is usually the last resort you should use.
The order of choice is to write your own class, if it didn’t work out, apply the templates, but if the templates didn’t fit, then only then sculpt the preprocessor.
And yes, if you lathered to declare constants through the preprocessor, crack your hands with the keyboard harder. There is constexpr for declaring constants .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question