#define directive as Macros Expressions
Understanding the purpose of #define pre-processor directive to be used as macros or use of replacement action for expressions
Learning Objectives
- Understanding the use of #define as a macro where a function like symbol structure form can be replaced with an expression with suitable use of function parameters.
Source Code
|
Run Output
Code Understanding
#define velocity(u,a,t) u+a*t
Here we write #define to define a function like syntax with a following expression where parameters passed to function have been used in the given expression.
int main(){
int v=velocity(5,2,3);
The defined macro has been used here with fixed values (we can pass variable names also if desired). Now this macro will return output as per expression given in the define macro.
cout<<v<<endl;
Output is printed
return 0;}
Notes
- #define macros can give immense possibility of dynamic compilation. This also helps in version control of C++ programs where not only expression values are easily definable but even expressions are definable.
Common Errors
- One must take care that expressions given as macro definitions must be workable. Compiler may not be able to check expression mistakes the way it checks for data types etc in case of regular expressions in the main code.
Suggested Filename(s): pp-mac.cpp, define-macros.cpp
sunmitra| Created: 2-Sep-2018 | Updated: 2-Sep-2018|