Why sizeof is an operator rather than macro or function

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • manjuks
    New Member
    • Dec 2007
    • 72

    #1

    Why sizeof is an operator rather than macro or function

    Hi All,

    Why sizeof is called as an operator, why it can not be function or a macro?
    My assumption is type information is available at compile time, and to find out the size we need the type of object. Is it correct? or tell me why it must be an operator?

    Thanks & Regards,
    Manjunath
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    It operates on types, neither functions or macros operate on types they operate on variables or constants.

    Only the compiler can determine the result of sizeof from parsing the code.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      sizeof is evaluated at compile-time. Functions are evaluated at run-time. Therefore sizeof can't be a function.

      In C, macros perform simple textual substitution. This means that any macro can be replaced by its expansion without altering the program. If sizeof were a macro, then what does it expand to? Sizeof can't be a macro.

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        And the sizeof operator only determines the size of the type or variable as it appears on the stack. That is, if you allocate memory on the heap using
        malloc():

        Code:
        MyStuff* var = malloc(1000);
        then

        Code:
        printf("%d", sizeof(var));
        gives you the size of the pointer and not the size of what it points at.

        Comment

        Working...