Below is the small program:
#include <stdio.h>
#define max 'A'
int main()
{
char a;
printf("max[%d] sizeof[max][%ld]\n", max, sizeof(max));
a = max;
printf("a[%d] sizeof[a][%ld]\n", a, sizeof(a));
return 0;
}
And the output of the program is:
max[65] sizeof[max][4]
a[65] sizeof[a][1]
Can anyone help me to understand why the sizeof(max) is 4 bytes?
Macros are not stored in memory anywhere in the final program but instead the code for the macro is repeated whenever it occurs.
Macro variable values have a maximum length of 65,534 bytes. The length of a macro variable is determined by the text assigned to it instead of a specific length declaration. So its length varies with each value that it contains. Macro variables contain only character data.
The sizeof in C is an operator, and all operators have been implemented at compiler level; therefore, you cannot implement sizeof operator in standard C as a macro or function. You can do a trick to get the size of a variable by pointer arithmetic.
During preprocessing, a macro is expanded (replaced by its definition) inline each time it's used. A function definition occurs only once regardless of how many times it's called. Macros may increase code size but don't have the overhead associated with function calls.
sizeof(max)
is replaced by the preprocessor with sizeof('A')
. sizeof('A')
is the same as sizeof(int)
, and the latter is 4 on your platform.
For the avoidance of doubt, 'A'
is an int
constant in C, not a char
. (Note that in C++ 'A'
is a char
literal, and sizeof(char)
is fixed at 1 by the standard.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With