Why are types always a certain size no matter its value?

后端 未结 19 1855
谎友^
谎友^ 2021-01-30 15:22

Implementations might differ between the actual sizes of types, but on most, types like unsigned int and float are always 4 bytes. But why does a type always occupy a certai

19条回答
  •  温柔的废话
    2021-01-30 15:48

    I like Sergey's house analogy, but I think a car analogy would be better.

    Imagine variable types as types of cars and people as data. When we're looking for a new car, we choose the one that fits our purpose best. Do we want a small smart car that can only fit one or two people? Or a limousine to carry more people? Both have their benefits and drawbacks like speed and gas mileage (think speed and memory usage).

    If you have a limousine and you're driving alone, it's not going to shrink to fit only you. To do that, you'd have to sell the car (read: deallocate) and buy a new smaller one for yourself.

    Continuing the analogy, you can think of memory as a huge parking lot filled with cars, and when you go to read, a specialized chauffeur trained solely for your type of car goes to fetch it for you. If your car could change types depending on the people inside it, you would need to bring a whole host of chauffeurs every time you wanted to get your car since they would never know what kind of car will be sitting in the spot.

    In other words, trying to determine how much memory you need to read at run time would be hugely inefficient and outweigh the fact that you could maybe fit a few more cars in your parking lot.

提交回复
热议问题