+ 2
Where is #define mostly useful?
Well I have read and mostly understood about the way it works, but can anyone explain to me when does it's use shine?
1 ответ
+ 6
It's used to create macros, which are sort of like find-and-replace for your code.
For example, without macros, you might write a max function like this:
int max(int a, int b);
What's the problem here, though? Our function only works with integers! What if we want to compare other things? Do we really have to write a comparison function for each data type?
No, we don't (assuming the comparison operators are defined for that type). We can do this instead:
#define max(a, b) ((a) > (b) ? : (a) : (b))
When you use this macro and compile your code, the preprocessor comes along and straight-up replaces code to look like what you defined the macro to be. So when it sees
max(6, 5);
it rewrites it as
((6) > (5) ? : (6) : (5))
This is why types don't matter! As long as they can be compared, it'll work. You can also see that this removes the overhead of a function call.
Also, you probably know you can create global constants like:
const int VAL = 5;
With macros, you can do:
#define VAL 5
The difference is that in the first case, VAL is a variable that exists on the stack. In the second case, all mentions of VAL in your code are just replaced with 5.
In conclusion, you can reduce some overhead by using them. Additionally, you can create constructs that are impossible using functions. For example:
#define until(x) while(!(x))
Which would be used like:
int x = 0;
until(x == 5)
++x;
// x now equals 5
By being really clever, you can save yourself a lot of work. If you wanted to be clever to the point of being stupid, you could make your own language within C++ just by using macros.