The #define in C++
Here is a short blog post that talk about the #define directive in C++
The #define is a preprocessor directive that the compiler calls during runtime. There are many preprocessor directives that are available in C++ that allows you to do all sorts of things. After defining these directives, they can be used from within the code.
Here's how you use #define in C++. In this case I'm looping the program 'a' times, printing "Hello" each time.
'LOOP' is the name of the identifier. After that comes the parameter it takes, which is 'a'. Note that you don't have to specify a data type.
Now from within your code, you can call this directive using :
Now this is the basics of the #define directive, but I will also talk about how the assert function can be used together with #define.
The assert function is basically a function that checks arguments. So if you wanted to, say, check if variable 'a' is bigger than variable 'b', then you can do so.
This is how you call this in your code:
That's all for this post, I'll be back with more.
The #define is a preprocessor directive that the compiler calls during runtime. There are many preprocessor directives that are available in C++ that allows you to do all sorts of things. After defining these directives, they can be used from within the code.
Here's how you use #define in C++. In this case I'm looping the program 'a' times, printing "Hello" each time.
'LOOP' is the name of the identifier. After that comes the parameter it takes, which is 'a'. Note that you don't have to specify a data type.
Now from within your code, you can call this directive using :
You cannot, though try saying 'LOOP("A"); and hope it to work. The compiler will point out that they are incompatible types.
Now this is the basics of the #define directive, but I will also talk about how the assert function can be used together with #define.
The assert function is basically a function that checks arguments. So if you wanted to, say, check if variable 'a' is bigger than variable 'b', then you can do so.
This is how you call this in your code:
This can compare if 2 is greater than 4 and if it returns false, then the program runs, else it aborts.
Note: remember to include the cassert library like this : #include <cassert>
That's all for this post, I'll be back with more.
Comments
Post a Comment