Is sizeof Operator in C Evaluate the Expression for Determining its Size

Question: Is sizeof Operator in C Evaluate Expression for Determining its Size?

Answer: Firstly we consider a simple example:

/* 
 * sizeof_eval_exp.c -- program displays if sizeof evaluates an expression
 * as operand
 */
#include <stdio.h>
int main(void)
{
    int a = 1;
    int arr[10] = {1,2,3,4,5,6,7,8,9,10};
 
    printf("size of int a and value of a in sizeof (a = 5) is %d bytes "
           "%d\n", sizeof (a = 5), a);
 
    printf("size of int a and value of a in sizeof (a++) is %d bytes %d\n",
            sizeof a++, a);
 
    printf("size of arr and value of int arr[5] in sizeof (arr) is %d bytes"
           " %d\n", sizeof (arr), arr[5]);
 
    printf("size of arr and value of int arr[0] in sizeof (arr[0] = 10) is "
           "%d bytes %d\n", sizeof (arr[0] = 10), arr[0]);
 
        return 0;
}

We observe in above program, a, which is an integer, assigned value 1 during initialization. When used in exp. (a = 5) & passed to sizeof operator, results size as 4 bytes, which has to be for integer type on Linux, while value of a remains 1 and not 5. Therefore, sizeof doesn’t evaluate the expression as operand to sizeof operator. Similarly, when (a++) is passed to sizeof operator, it returns size as 4 bytes but value of a as 1. Reasoning for other statements is alike as before.

Actually, what happens is that when some expression is passed to sizeof operator, it returns the size of the type of first term in the expression and expression isn’t evaluated at all.

The general syntax of sizeof operator

advertisement
advertisement
    sizeof unary-expression;    /* any variable, array, structure etc. */
    sizeof (datatype);

Sanfoundry Global Education & Learning Series – 1000 C Tutorials.

If you wish to look at all C Tutorials, go to C Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.