1

So I was trying to get the size of a struct on my C program and write the following code:

typedef struct Msg_Header Msg_Header; // the struct Msg_Header was defined earlier

int size = sizeof Msg_Header;

This produced a compilation error I cant understand. In order for this to work I found that I must user parenthesis like that:

int size = sizeof(Msg_Header);

This is weird since sizeof works perfectly on simple variable types like int without parenthesis, same weird behaviour accures when I use struct Msg_Header instead if the alias.

Can someone explain what is going on here?

EDIT: The compilation error says: "expected expression before Msg_Header"

antonpuz
  • 3,256
  • 4
  • 25
  • 48

2 Answers2

1

The sizeof operator can be used without parantheses only in case of expressions, not types (nor type synonyms created by typedef keyword) itself. See following example for possible valid usage:

#include <stdio.h>

struct Msg_Header { // struct tag
    int n;
};

typedef struct Msg_Header Msg_Header; // typedef synonym

int main(void) {
    Msg_Header msg_header;

    printf("%zu\n", sizeof(struct Msg_Header));
    printf("%zu\n", sizeof(Msg_Header));
    printf("%zu\n", sizeof msg_header);

    return 0;
}

Life sample here: http://ideone.com/tMB5cY

Grzegorz Szpetkowski
  • 36,988
  • 6
  • 90
  • 137
1

Although sizeof is an operator and not a function, when used with a type you need the parentheses. Basically you hand it a type-cast of the type, which requires parentheses.

From the standard 6.5.3 Unary operators:

unary-expression:
    postfix-expression
    ++ unary-expression
    -- unary-expression
    unary-operator cast-expression
    sizeof unary-expression
    sizeof ( type-name )
ooga
  • 15,423
  • 2
  • 20
  • 21