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.
If that's really what the instructor said then there is indeed no justification for it.
It makes no sense to me, 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?
Neither the C nor the C++ language standard provides any justification for the claim, and in practice, it is not descriptive of of real-world implementations.
But really, the terms in which the claim is stated need to be challenged before we even get to that. In C, a "constant" is a literal numeric or null pointer value appearing in source code. The language implementation has free rein to combine constants algebraically, to encode them into instructions rather than data, and to perform other transformations that effectively mean that the constant does not correspond to any storage at all. Where constants do have a corresponding representation in runtime memory, that representation is indeed bound by the system architecture, and I do not know any current computer architecture that can address storage in units smaller than eight bits.
If we suppose, however, that instead of the instructor being flagrantly wrong, there was instead some kind of miscommunication, there is a way to describe storage consisting of fewer than eight bits: structure types can have members called "bit fields", which have integer type and a specified number of bits. Example:
struct example {
unsigned int two_bits:2;
};
Bit fields are not themselves addressible -- you may not apply the address-of operator (&
) to them -- and the language acknowledges that their storage is part of one or more anonymous "addressible storage units" that are typically larger, but the representation of each bit field member of a structure object is defined to consist of the specific number of bits declared for it.