C++ global const question
-
Hi Let's say I defined a global const in a header file (which will be #included by many files) as follows: const int MAX_CLIENT = 1000; My question is, will the compiler replace each occurence of MAX_CLIENT with 1000? Should I declare MAX_CLIENT as static const instead? And will the same rule apply if MAX_CLIENT is not an int, but a char array? Thanks!
-
Hi Let's say I defined a global const in a header file (which will be #included by many files) as follows: const int MAX_CLIENT = 1000; My question is, will the compiler replace each occurence of MAX_CLIENT with 1000? Should I declare MAX_CLIENT as static const instead? And will the same rule apply if MAX_CLIENT is not an int, but a char array? Thanks!
Indrawati wrote: will the compiler replace each occurence of MAX_CLIENT with 1000? Yes and no :). It's not a direct textual substitution like a
#define
, but when the compiler is optimising code it will substitute the variable reference by its value. Indrawati wrote: Should I declare MAX_CLIENT as static const instead? If your header file is used by multiple source files, then yes, otherwise you'll get a bunch of multiple initialisation errors from the linker. Indrawati wrote: And will the same rule apply if MAX_CLIENT is not an int, but a char array? Yes. If it's achar*
though, such aschar *message = "Message"
, then make it fully constant, ie.const char * const message = "Message"
, otherwise the compiler might not treat it as a true constant.Ryan
"Punctuality is only a virtue for those who aren't smart enough to think of good excuses for being late" John Nichol "Point Of Impact"