If a value is开发者_StackOverflow社区 defined as
#define M_40 40
Is the size the same as a short
(2 bytes) or is it as a char
(1 byte) or int
(4 bytes)?
Is the size dependent on whether you are 32-bit or 64-bit?
#define
has no size as it's not a type but a plain text substitution into your C++ code. #define
is a preprocessing directive and it runs before your code even begins to be compiled .
The size in C++ code after substitution is whatever the size is of what C++ expression or code you have there. For example if you suffix with L
like 102L
then it is seen a long, otherwise with no suffix, just an int. So 4 bytes on x86 and x64 probably, but this is compiler dependent.
Perhaps the C++ standard's Integer literal section will clear it up for you (Section 2.13.1-2 of the C++03 standard):
The type of an integer literal depends on its form, value, and suffix. If it is decimal and has no suffix, it has the first of these types in which its value can be represented: int, long int; if the value cannot be represented as a long int, the behavior is undefined. If it is octal or hexadecimal and has no suffix, it has the first of these types in which its value can be represented: int, unsigned int, long int, unsigned long int. If it is suffixed by u or U, its type is the first of these types in which its value can be represented: unsigned int, unsigned long int. If it is suffixed by l or L, its type is the first of these types in which its value can be represented: long int, unsigned long int. If it is suffixed by ul, lu, uL, Lu, Ul, lU, UL, or LU, its type is unsigned long int
A plain integer is going to be implicitly cast to int
in all calculations and assignments.
#define
simply tells the preprocessor to replace all references to a symbol with something else. This is the same as doing a global find-replace on your code and replacing M_40
with 40
.
A #define value has no size, specifically. It's just text substitution. It depends on the context of where (and what) is being substituted.
In your example, where you use M_40
, the compile will see 40
, and usually treat it as in int
.
However, if we had:
void SomeFunc(long);
SomeFunc(M_40);
It will be treated as a long.
Preprocessor macros get literally swapped in during the preprocess stage of the compilation.
For example the code
#define N 5
int value = N;
will get swapped for
int value = 5;
when the compiler sees it. It does not have a size of its own as such
The preprocessor just does simple text substitution, so the fact that your constant is in a #define
doesn't matter. All the C standard says is that "Each constant shall have a type and the value of a constant shall be in the range of representable values for its type." C++ is likely to not vary too much from that.
精彩评论