Reputation: 13257
I am trying to pass a type in C macro, But I am getting error.
#include <stdio.h>)
int size = 0;
#define SIZEOF(TYPE) \
TYPE _array_[2]; \
size = (char*)(&_array_[1]) - (char*)(&_array_[0]);
int main(int argc, char** argv, char** envp) {
int array[2];
int x = SIZEOF(int);
printf("Size Of Integer = %d", SIZEOF(int));
return 0;
}
Upvotes: 0
Views: 203
Reputation: 141554
Macro expansion is a text replacement. Your code expands to:
int x = int _array_[2]; size = (char*)(&_array_[1]) - (char*)(&_array_[0]);
The initial part int x = int
is a syntax error.
You could make your code work without changing the macro by writing:
SIZEOF(int);
printf("Size Of Integer = %d", size);
An improvement would be to pass the name of the variable as a parameter to the macro, instead of using global variables.
Upvotes: 3
Reputation: 4314
Try this:
#define SIZEOF(TYPE) \
({ \
TYPE _array_[2]; \
(char*)(&_array_[1]) - (char*)(&_array_[0]); \
})
...although it uses gcc specific support for statements inside expressions, so I would recommend using the standard sizeof
operator instead.
How to actually use this:
printf("Size Of Integer = %d", (int)SIZEOF(int));
i.e. it works as a pretty good replacement for sizeof
on compilers that actually allow the dirty trick of statements inside expressions.
Upvotes: 1