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
#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.
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.
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.
577 Who developed the "avformat-59.dll" that comes with FFmpeg?
925 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
585 PHP ssh2_scp_send fails to send files as intended
574 rails db:create error: Could not find mysql2-0.5.4 in any of the sources
626 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.