-3

I have seen following examples in test your c(Author : Yashvant Kanetkar).

In following example, sizeof() gives the output 8.

#include<stdio.h>

double d;

int main()
{
(int)(float)(char)d;
printf("%d\n",sizeof(d));
}

But in second example, sizeof() gives the output 4.

#include<stdio.h>

double d;

int main()
{
printf("%d\n",sizeof((int)(float)(char)d));
}

Why both output different? There is no explanation in book.

msc
  • 33,420
  • 29
  • 119
  • 214
  • 6
    `(int)(float)(char)d;` In the first example this line has no effect. So it ends up as `sizeof(double)`. In the second example you have `sizeof(int)`. – DeiDei Feb 21 '17 at 16:20
  • 2
    Please throw that book, it's not teaching you anything useful. – Sourav Ghosh Feb 21 '17 at 16:21
  • 2
    Not only does `(int)(float)(char)d;` have no effect regarding your ensuing `sizeof` usage; it has no effect *whatsoever*. it is a pointless line of code. A reasonable C compiler with high enough warnings will give you a hint to that effect; clang, for example, "main.c:16:5: Expression result unused" – WhozCraig Feb 21 '17 at 16:23
  • 4
    [`sizeof` returns `size_t` which must be printed out using `%zu`](http://stackoverflow.com/q/940087/995714) – phuclv Feb 21 '17 at 16:24
  • 2
    Please do not change question once you've received answer, it makes the answers look invalid. – Sourav Ghosh Feb 21 '17 at 16:41

2 Answers2

9

The first case is equivalent to sizeof(double). The casts, are useless there. the effective type of d remains unchanged. Compile your code with proper warnings enabled and you'll see some warnings like

warning: statement with no effect [-Wunused-value]

The second one is equivalent to sizeof(int), the casts are effective.

You are seeing the results (size of an int or double) based on your platform/ environment.

That said,

  • sizeof yields a result of type size_t, you must use %zu format specifier to print the result.
  • The conforming signature for main() in a hosted environment is int main(void), at least.
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1

In the first instance the sizeof operator returns the size of double. In the second instance, it returns the size of int.

Reason

In the first instance,

(int)(float)(char)d; //This doesn't do anything effective.
printf("%d\n",sizeof(d)); //d is still `double`.

In the second instance,

//You are type casting d to float and then to int and then passing it to the operator sizeof which now returns the size of int. 
printf("%d\n",sizeof((int)(float)(float)d)); //d is `int` now when passed to `sizeof`.
VHS
  • 9,534
  • 3
  • 19
  • 43