Bit, bytes and possibilities

Hello,

it says: " Recall that a variable occupies several bytes in memory determined by its type. In this case, the array has five integers each of which occupies four bytes of memory; therefore the total size is 5 x 4 = 20 bytes"

I am trying to understand a little bit more how it works.
From what I know: 1byte = 8 bits = 2^8 = 256 possibilities
So 4 bytes means 256 * 256 * 256 * 256 = 4 294 967 296 possibilities

If we can store only 4 294 967 296 different integers, it looks like we re limitedâ€¦I think I miss something, some one to show me the light?

2 Likes

Youâ€™re right that that type does have limits to the range of values you can actually store, however regardless of the type you choose- Arithmetic types - cppreference.com you cannot store arbitrarily large numbers with fixed precision types. The header `limits.h` can help you find the limits for various types: Numeric limits - cppreference.com

The following might be a decent intro to arbitrary compared to fixed point types but other resources exist if you hunt around- Arbitrary-precision arithmetic - Wikipedia (it also links to a few pieces of software that allow for arbitrary precision when itâ€™s not natively supported by a language).

As a side note the size of `int` isnâ€™t strictly limited to `4` bytes and it can vary by platform/compiler. Itâ€™s a bit confusing at first. The limits will also vary based on the type being signed or unsigned (do you also need to represent negatives, if so the range is not the same). Might be worth having a web search for this as itâ€™s a topic that comes up often so thereâ€™s some good resources out there for wrapping your head around it.

2 Likes

Nice, thank you for those hints. I think I start to understand a bit more why C is reputed to be efficient in term of resources management. I learnt Python before to start this class, I see some good habits to acquire by learning this language.

1 Like

Itâ€™s a great question; a bit of a rabbit hole in terms of what you need to grasp for it all to make sense but even getting an overview is a good thing .