Hello,
In my desire to learn something a bit more low level than Java I have recently reached/considered two languages: C and Zig. Here I would like to question if my understandings about memory allocation in C are correct, and how to optimize a fictional program.
If I'm not mistaken, C int occupy 32 bits, correct? Are 32 bits allocated even if one has a value that could be stored in less bits? e.g. 5 in 3 bits.
This caught my attention because in Zig you can specify an arbitrary memory size for a variable. For the previous example one could use a u3 which allocates an unsigned integer variable with 3 bits of space.
Suppose a fictional program that simply puts in memory 1 billion integer variables with value 5. As 3 bits are needed to express this value, the program requires at least 3 billion bits, or around 358MB. In Zig it seems one could allocate exactly that, but in C it seems one cannot? After googling for Data Types in C it appears the least amount of memory a variable occupies would be 8 bits, and it seems to be possible to compile and run the following code:
int main() {
char test = 5;
printf("%d", test);
return 0;
}
By this approach the program would require around 954MB of memory, almost 3x more than in Zig. Also, in my personal belief it feels a bit odd to assign the value to a variable of type char.
So my questions are: Have I made any wrong assumptions/considerations? Is there a way possible to optimize this fictional program in C so it would use the same amount of memory as if it were written in Zig? Where could I read and learn about this?
Thank you.