+ 2

#define and const differences

What is better in C and C++ to define constants? What are advantages of each method? #define PI 3.14 or const double PI 3.14

6th Jul 2020, 5:18 PM
Maksim
Maksim - avatar
1 Odpowiedź
+ 5
#define is a preprocessor directive. Things defined by #define are replaced by the preprocessor before compilation begins. const variables are actual variables like other normal variable. The big advantage of const over #define is type checking. We can also have poitners to const varaibles, we can pass them around, typecast them and any other thing that can be done with a normal variable. And also #define replaces some text in program Any how I would say const would better if you go with type checking (pointers and data types) and #define if you want to replace content , and have fast replacement of const's .
6th Jul 2020, 5:47 PM
Nikhil Maroju
Nikhil Maroju - avatar