why sizeof(13.33) is 8 bytes?

可紊 提交于 2019-11-30 08:59:40

问题


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?


回答1:


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.




回答2:


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




回答3:


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

Try 13.33f instead.




回答4:


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!




回答5:


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).



来源:https://stackoverflow.com/questions/5537276/why-sizeof13-33-is-8-bytes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!