ClassHacker
ClassHacker

Reputation: 394

Why is the sizeof operator working differently for some expressions?

I know that expressions like x++ or function calls don't get evaluated in the sizeof operator.

When I ran the below code, I got 4 8 8 as output. Can somebody explain to me what is actually happening on lines 6,7,8?

#include <stdio.h>
int main()
{
  int x=10;
  double y=10.0;
  printf("%d ",sizeof (x=x+y));    
  printf("%d ",sizeof (y=x+y));     
  printf("%d ",sizeof (x+y));
  return 0;
}

I figured out that if an expression contains an assignment operator = implicitly (like pre-increment) or explicitly (like x=x+y) , then the expression doesn't get evaluated in the sizeof operator.

Am I right?

Upvotes: 3

Views: 186

Answers (3)

Sourav Ghosh
Sourav Ghosh

Reputation: 134386

sizeof operator operates on the datatype of the argument. In your code

  • expression (x=x+y) yields a type int, same as x
  • expression (y=x+y) yields a type double, same as y
  • expression x+y yields a type double, as per usual arithmetic conversion rules.

The sizes are calculated based on this.

In your platform, it's likely that sizeof(int) is 4 and sizeof(double) is 8, so you're seeing corresponding output.

That said, sizeof yields a result of type size_t, you must use %zu format specifier to print the result.

Upvotes: 9

Robin Hellmers
Robin Hellmers

Reputation: 257

sizeof evaluates the type.

x is an int and seems to have the size of 4 bytes on your system.

y is a double and seems to have the size of 8 bytes on your system.

sizeof (x+y) will evaluate to the largest of the two, thereby double and 8 bytes.

x=x+y is is still an int as there will be a conversion to int type from the double x+y.

Thereby sizeof (x=x+y) is 4 bytes.

y=x+y is still an double as x+y is of the type double.

Thereby sizeof (y=x+y) is 8 bytes.

Upvotes: 3

Nikola
Nikola

Reputation: 125

Expressions are evaluated, just results of those evaluations differ:

x=x+y

can be readed as:

int = float + int

What happens is, that result is calculated and then turncated to int and therefore you get the result 4: sizeof(int) = 4.

Second line is simmilar but with float.

On the last line you calculate sizeof (float + int) which is equal to sizeof(float) = 8.

Upvotes: -2

Related Questions