#define directive – Preprocessor for Names to constant replacement
Understanding the purpose of #define pre-processor directive.
Learning Objectives
- Understanding the use of #define for the purpose of symbol to constant value replacement.
Source Code
|
Run Output
Code Understanding
#define PI 3.1416
Here we define a symbol called PI. Whenever PI occurs in a program (not inside string literals etc) it will be replaced by a value 3.1416
#define R 5
Here another symbol R has been defined which will be replaced by value 5
int main(){
double area=PI*R*R;
double circum=2*PI*R;
Here both PI and R will be replaced by 3.1416 and 5 respectively while compilation
cout<<“Area of circle with radius “<<R
<<” = “<<area<<endl;
cout<<“Circumference of circle with radius “<<R
<<” = “<<circum<<endl;
In both the above statements R will be replaced by 5. Notice that R is not a variable but it is a predefined value known only to the compiler and it is not relevant at runtime.
return 0;
}
Notes
- #defines are powerful ways of value replacements at the time of compilation. But some people do not like them as they do give importance to their data type. Data type errors if any will not be detectable at compile time.
Common Errors
- Notice that #define lines in the C++ program are not actually statements in true sense, that is why you should not put a semicolon (;) character at the end.
Suggested Filename(s): pp-def.cpp, define-directive.cpp
sunmitra| Created: 1-Sep-2018 | Updated: 1-Sep-2018|