Just do something like this: #ifdef USE_CONST #define MYCONST const #else #define MYCONST #endif Then you can write code like this: MYCONST int x = 1; MYCONST char* foo = "bar"; and if you compile with USE_CONST defined (e.g., typically something -DUSE_CONST in the makefile or compiler options) then it will use the consts; otherwise it won't.
What is the point of #define in C++? I've only seen examples where it's used in place of a "magic number" but I don't see the point in just giving that value to a variable instead.
The #define directive is a preprocessor directive; the preprocessor replaces those macros by their body before the compiler even sees it. Think of it as an automatic search and replace of your source code. A const variable declaration declares an actual variable in the language, which you can use... well, like a real variable: take its address, pass it around, use it, cast/convert it, etc. Oh ...
0 in C or C++ #define allows you to create preprocessor Macros. In the normal C or C++ build process the first thing that happens is that the PreProcessor runs, the preprocessor looks though the source files for preprocessor directives like #define or #include and then performs simple operations with them.
#define simply substitutes a name with its value. Furthermore, a #define 'd constant may be used in the preprocessor: you can use it with #ifdef to do conditional compilation based on its value, or use the stringizing operator # to get a string with its value.
Is it better to use static const variables than #define preprocessor? Or does it maybe depend on the context? What are advantages/disadvantages for each method?
2 #define is part of something called the "preprocessor." Essentially, this is the code that is processed before the C document is compiled. Most of the preprocessor code is in a file with a ".h" extension (which is why you may have seen that when importing libraries). The preprocessor language is primitive.
What is the scope of a #define? I have a question regarding the scope of a #define for C/C++ and am trying to bet understand the preprocessor. Let's say I have a project containing multiple sour...
As far as I know, what you're trying to do (use if statement and then return a value from a macro) isn't possible in ISO C... but it is somewhat possible with statement expressions (GNU extension). Since #define s are essentially just fancy text find-and-replace, you have to be really careful about how they're expanded. I've found that this works on gcc and clang by default:
I have been seeing code like this usually in the start of header files: #ifndef HEADERFILE_H #define HEADERFILE_H And at the end of the file is #endif What is the purpose of this?