Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does sizeof(MACRO) give an output of 4 bytes when MACRO does not hold any memory location?

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?

like image 628
Sunny Gupta Avatar asked May 14 '18 15:05

Sunny Gupta


People also ask

Does macro occupy memory?

Macros are not stored in memory anywhere in the final program but instead the code for the macro is repeated whenever it occurs.

How many bytes is a macro?

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.

Can you use sizeof in a macro?

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.

Does macros increase code size?

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.


1 Answers

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.)

like image 138
Bathsheba Avatar answered Oct 11 '22 11:10

Bathsheba