Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How much allocated space do constants have?

Tags:

c++

c

constants

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.

like image 223
DarkoNaito_09 Avatar asked Dec 14 '25 04:12

DarkoNaito_09


2 Answers

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.

like image 106
0___________ Avatar answered Dec 16 '25 20:12

0___________


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.

like image 31
chux - Reinstate Monica Avatar answered Dec 16 '25 20:12

chux - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!