8

When I give sizeof(a), where a=13.33, a float variable, the size is 4 bytes. But if i give sizeof(13.33) directly, the size is 8 bytes.

I do not understand what is happening. Can someone help?

Christian Rau
  • 45,360
  • 10
  • 108
  • 185
karthik
  • 17,453
  • 70
  • 78
  • 122
  • 14
    Dude, stop adding and removing the `math` tag to bump this question to the top. – Xeo Apr 12 '11 at 11:49
  • 1
    try 13.ff instead and also refer this link http://stackoverflow.com/questions/2331751/does-the-size-of-an-int-depend-on-the-compiler-and-or-processor –  Dec 18 '13 at 08:52
  • [Why floating point value such as 3.14 are considered as double by default in MSVC?](https://stackoverflow.com/q/4353780/995714) – phuclv Aug 21 '17 at 09:06

5 Answers5

44

Those are the rules of the language.

13.33 is a numeric literal. It is treated as a double because it is a double. If you want 13.33 to be treated as a float literal, then you state 13.33f.

13.33 is a double literal. If sizeof(float) == 4, sizeof(13.33f) == 4 should also hold because 13.33f is a float literal.

karthik
  • 17,453
  • 70
  • 78
  • 122
19

The literal 13.33 is treated as a double precision floating point value, 8 bytes wide.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 2
    To explicitly mark a number literal as a single precision float, try `13.33f`. `sizeof(13.33f)` returns the expected 4. – Mike Welsh Apr 04 '11 at 10:37
13

The 13.33 literal is being treated as 'double', not 'float'.

Try 13.33f instead.

Will Dean
  • 39,055
  • 11
  • 90
  • 118
9

The type and size of your variable are fine. It's just that the compiler has some default types for literals, those constant values hard-coded in your program.

If you request sizeof(1), you'll get sizeof(int). If you request sizeof(2.5), you'll get sizeof(double). Those would clearly fit into a char and a float respectively, but the compiler has default types for your literals and will treat them as such until assignment.

You can override this default behaviour, though. For example:

2.5 // as you didn't specify anything, the compiler will take it for a double.
2.5f // ah ha! you're specifying this literal to be float

Cheers!

salezica
  • 74,081
  • 25
  • 105
  • 166
8

Because 13.33 is a double, which gets truncated to a float if you assign it. And a double is 8bytes. To create a real float, use 13.33f (note the f).

Xeo
  • 129,499
  • 52
  • 291
  • 397