My IT teacher said that when space is allocated for a constant in C and C ++ only the STRICTLY necessary space is allocated: he said that if we store the value 12 in a constant, for example, only 4 bits of memory will be allocated. I believe this is not true, both because the memory is almost always divided into 8-bit "cells", and because when we declare a constant we also indicate its type, so we decide how much memory to dedicate to it. Any expert opinion?
PS: He was talking about constants declared with the const qualifier.
Of course your IT teacher is wrong. The size depends on the type of the const value. But you must also remember that any objects can be removed by the optimizing compiler if the they are not needed.
both because the memory is almost always divided into 8-bit "cells"
That's data memory is usually in 8-bit cells.
With int x = 12 in C, the constant 12 is not specified to be store in memory as data. All that is required is the x takes on the value of 12 - somehow.
The 12 could be embedded as part of an instruction - possibly only a few bits.
Some instruction sets allow small values to be stored in a few bit of the emitted code and not memory thus using zero bytes of data memory.
This commonly happens with special values like 0. There is no 0 stored someplace taking up 8 bits of data as likely there is an instruction to simply "clear" x.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With