What is the difference between const and define?

Asked 2 years ago, Updated 2 years ago, 66 views

How do you use these two differently?
Should I unify it to one of them?

I may have skipped it when I was getting started, but I don't remember it at all

c++ preprocessor

2022-09-30 20:54

3 Answers

#define is deployed by the preprocessor (What is the clear difference between declaration and definition, include)?

Therefore, only the deployment results are passed to the compiler and the original information is not left.For example, you may not be able to see it when debugging.

Conversely, you can take advantage of the deployment process before compilation.

#define hello "Hello"
#define WORLD "World"
char message[] = expanded and combined with hello", "WORLD"."; // "Hello, World."

You can expand the string as shown in , and combine one string at compile time (in the case of const, each is an independent constant and cannot be combined at compile time).It will merge at runtime in some other way.)

Each has its own advantages and disadvantages, so use it in the right place.


2022-09-30 20:54

const is used to declare variables.
There is a container and the contents are fixed.

define replaces all strings with the specified values.

The difference is whether to replace it before compilation or not

addition:
I didn't know where to use it.
I don't really care about it, but
const sounds more like a C language.
(const when you start using the pointer, or when you don't want to change the memory address)
However, you must use define if you want to use constants in case of the switch statement.
Depending on the time and situation, considering that define replaces it before compilation, I think I can see how to use it.
I am const in the basic C language system.


2022-09-30 20:54

Consider #define to be copied or replaced in the early stages of compilation
Therefore, after definition, it will continue to exist like a global variable.
const exists only as a variable, so the concept of storage space can be adapted and maintained.
If #define already defines a constant, you must use #undef if you think it has to be the same name for readability. If such a code occurs, you may change it by mistake when changing it.Such a situation must be avoided.From this point of view, I think const will allow you to write more liberal code.


2022-09-30 20:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.