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

Output:

 Differences between #define & const in C/C++

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

Output:

 Differences between #define & const in C/C++

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)

Output:

 Differences between #define & const in C/C++

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.

Pin It on Pinterest

Share This