liv2hak
liv2hak

Reputation: 15010

expected expression before do. macro using do while loop

I have implemented my custom sizeof operator as below

#define my_sizeof(x) do{\
    typeof(x) _a;\
    (char*)(&_a + 1) - (char*)(&_a);\
}while(0)

If I compile it I get the error

test.c:26:22: error: expected expression before ‘do’

Can't figure out what I am doing wrong.

My main function is given below.

int main()
{
   int a;

   unsigned long long b;
   double c;

   printf("size of a %zd \n",my_sizeof(a));
   printf("size of b %zd \n",my_sizeof(b));
   printf("size of c %zd \n",my_sizeof(c));
   return 0;
}

Upvotes: 1

Views: 12582

Answers (3)

syntagma
syntagma

Reputation: 24344

This is because of the way you macro is preprocessed. The preprocessor output (which you may get using gcc -E file.c) will look like this (stripped for a variable only):

int main() {
    int a;
    printf("size of a %zd \n", do { typeof(a) _a; (char*)(&_a + 1) - (char*)(&_a); } while (0));
    return 0;
}

which is not a correct C syntax. You could use do..while macro like that though (without an assignment or nesting it inside another function):

MY_MACRO(x);

Refer to this article for some more information.

Upvotes: 3

John Bollinger
John Bollinger

Reputation: 181624

Your macro expands to a do loop. A do loop is not an expression, and does not produce a value. The compiler is telling you that you cannot use a do loop where you are trying to use one, and it is right.

There is no clean alternative in C, since you cannot declare a variable inside an expression.

Upvotes: 4

Carl Norum
Carl Norum

Reputation: 225182

A do/while loop can't return a value. You could instead use a GCC-style statement expression to do what you're trying:

#define my_sizeof(x) ({              \
    typeof(x) _a;                    \
    (char*)(&_a + 1) - (char*)(&_a); \
})

Clang & GCC support statement expressions for sure, I don't know about any other compilers off the top of my head.

Upvotes: 1

Related Questions