Differences between #define & const in C/C++
Differences between #define & const in C/C++
A preprocessor directive is #define. The preprocessor replaces things defined by #define prior to starting compilation.
In this chapter, we'll learn about the member, variable, and macro definition of const data. Const and #define are both used in source code for handling constants, but they have few differences.
#define is a preprocessor, while const is keyword
#define is used to identify these values with a tag, this set string is known in C++ as a macro description, while const is a keyword used it to consistent the identification value.
#define does not control scope, while const is controlled scope
Macro can be used to include the relevant header file anywhere in the program or in other files; therefore macros are not constrained by scope, but the constant can be specified within the feature and can therefore only be accessible within the feature/domain where constant is listed, so we can conclude that const member is also managed by sector.
The use of const is often good for practice. Since we can monitor their distance when using const. When placed inside each user defines feature, its effects will be limited to the component, and if placed outside of these user defines operations, then all files are universal.
C++ example, demonstrating use of #define and const
#include <iostream> using namespace std; //macro definition #define P 80 //global integer constantt const int K = 25; int main() { //local ineteger constant` const int T = 55; cout<<"Value of K: "<<K<<endl; cout<<"Value of P: "<<P<<endl; cout<<"Value of T: "<<T<<endl; return 0; }
Output:
K is a global symbolic constant in the above program but is pre-processed before compilation and P and also global constant, whereas T is local for the main function.
Macros (#define) can be redefined, but const cannot.
Macro (defined) can be reinvented anywhere in the system (by undefining and then defining), but constant cannot be redefined or reinvented even if we cannot reallocate the value in constant.
C++ Example, to redefine a defined Macro
#include <iostream> using namespace std; //macro definition #define S 60 int main() { cout<<"Value of S: "<<S<<endl; #undef S #define S 600 cout<<"Value of S: "<<S<<endl; return 0; }
Output:
You can see here that we modified the value of S, and it successfully executed the program as well as changes the value.
C++ Example, to redefine (re-assign) a content - (ERROR)
#include <iostream> using namespace std; //constant int const int T=30; int main() { cout<<"Value of T: "<<T<<endl; T=200; //error, we can not assign value to const cout<<"Value of T: "<<T<<endl; return 0; }
Output:
You can see here that we did not affect the periodic value, rather here we've tried to change T 's value, and there's a compilation error.