should i use the latter
should consteval or constinit be used instead for values derived from functions |
A macro is basically a "search-and-replace" that the preprocessor does.
With your macro you have plain literal constants in your code.
With declared variable you have explicit type associated with the "literal constant".
The compiler does use that additional metadata. Same with const, constexpr, constinit, consteval.
They express, describe, and narrow down; help compiler to point out unintended.
1 2 3
|
struct Sample {
int example() const;
};
| |
That const tells the user that Sample does not change when they call example(). That they can call example() on constant object.
That const lets the compiler to tell the writer of example()'s implementation:
Hey! Do not tweak self!
Similar specialization:
C has one cast. A sledgehammer. C++ has multiple casts. Precision tools.
Yes, it is better to leave macros to where they are necessary (or substantially simpler). Agent max's loop is not.
Yes, specifiers let you be more strict (and probably more optimized).
@agent max:
1. How much space do you save when you write:
1 2 3
|
#define loop(count) for(int i=0;i<count;++i)
loop (4)
| |
and not just
for(int i=0;i<count;++i)
2. How do I know, when I see code:
1 2 3 4
|
loop (4)
{
std::cout << "loop " << i+1 << " ";
}
| |
where to look for explanation. Some projects have millions of lines of code and multiple maintainers; the define might not be near.