educative.io

Data type modifiers -- short

I just wonder why if originally int have 4 byte, why would we want to decrease into 2 bye ? I mean, what is the objective of doing so ?


Course: https://www.educative.io/courses/cpp-basics
Lesson: https://www.educative.io/courses/cpp-basics/N8orOR5N6vD

Hi @Sean_Chrollo !!
The objective of using a smaller data type like “short” (which reserves 2 bytes) instead of the larger “int” data type (which reserves 4 bytes) is to save memory when the range of values needed for a particular variable is within the smaller data type’s range.

For example, if you know that the values a variable will hold will always be relatively small and fall within the range of -32,768 to 32,767 (which is the range of a signed short), using a short data type can save memory compared to using an int data type, which has a much larger range (-2,147,483,648 to 2,147,483,647 for a signed int).

By using smaller data types where appropriate, you can reduce memory usage in your program, which can be beneficial, especially in resource-constrained environments or when dealing with large datasets. It’s a trade-off between the range of values you need to store and the amount of memory you want to save. If the range of values required is larger than what a short can accommodate, then using int or other larger data types would be more appropriate.
I hope it helps. Happy Learning :blush: