Of int, char, float, and bool, which is smallest?

2019-03-11 18:28发布

The following is from a "fill-in at home" programming test that is part of the application process for an MSc in game development at a UK university:

C++ Basics

If a program declared four variables, one of type int, one of type float, one of type char, and one of type bool, which variable would occupy the least space in memory?

  1. int
  2. char
  3. float
  4. bool

According to the instructions, there is only one true statement. However, my C++ book (C++ Pocket Reference, O'Reilly) states: "The typical size of a bool is one byte," and "The size of a char is one byte. The size of a byte technically is implementation defined, but it is rarely anything but eight bits."

Am I misunderstanding something here? What answer would you put and why?

标签: c++ types
10条回答
We Are One
2楼-- · 2019-03-11 18:40

No type takes less than char, because by definition sizeof(char) == 1. However, it is entirely possible that all types take the same amount of space.

(Representing each type with 16 bits (with a suitably unusual floating point format) would suffice to satisfy the standard value range requirements; real hardware where every type has 32 bits exists.)

查看更多
老娘就宠你
3楼-- · 2019-03-11 18:45

The language doesn't specify any relationships between these type sizes that guarantee a correct answer to that question as posed. They could all be 32-bit types, for example.

查看更多
做个烂人
4楼-- · 2019-03-11 18:47

If a program declared four variables, one of type int, one of type float, one of type char, and one of type bool, which variable would occupy the least space in memory?

The real problem with the question your have posted lies in these words:

occupy ... space in memory

If an interpretation is to be assumed, then in most occasions you would assume one of the current popular compilers in which case answer 2 and 4 would both occupy the least space in memory. Simply because the current popular compilers make the char and bool occupy a single byte in memory...

As outlined in the comments, sizeof() is of type size_t, which is integral.

As sizeof(char) == 1 is always true as per the standard, and the value is integral; no other sizeof(T) can be lower than 1. But any other T than char can be bigger than 1 dependening on the implementation. As you can't assume that sizeof(char) == sizeof(bool) always holds, you can at least assume that sizeof(char) <= sizeof(bool) holds.

Which makes sizeof(char) being the least the most correct answer...

查看更多
狗以群分
5楼-- · 2019-03-11 18:49

I think the correct answer should be 2. By definition, char is the smallest addressable unit.

Also see: Why is a char and a bool the same size in c++?

查看更多
登录 后发表回答