Type size in c / c ++

I recently asked a question here regarding char size. Looking at my question, this led me to another question:
Are things like the number of bits in a char or sizeof(int) processor dependent on the OS, dependent on the compiler, or any combination of the above? Who decides sizeof(int) in my compiler 4?

EDIT: Let me explain: for example, my compiler on a 64-bit system uses 32bit int . Is this an installed compiler or operating system standard int for all compilers on this (exact) OS / platform combination? How about char = 8 bits? Can the OS decide what will use 16-bit characters? Can the compiler?

+6
source share
3 answers

In accordance with all ISO C standards, all sizes are measured in multiple char sizes. This means, by definition, sizeof(char) == 1 . The char bit size in bits is determined by the CHAR_BIT macro in <limits.h> (or <climits> ). The minimum char size is 8 bits.

Additional type restrictions:

 sizeof(char) <= sizeof(short int) <= sizeof(int) <= sizeof(long int) 

int should be able to represent from -32767 to +32767 - for example. It must be at least 16 bits.

C99 added a long long int , the size of which is greater than or equal to long int .

The rest is implementation dependent. This means that the C compiler in question chooses how large these numbers are.


How do C compilers choose these sizes?

There are some general conventions that most compilers adhere to. long often chosen as large as a machine word. On 64-bit machines, where CHAR_BIT == 8 (this is almost always the case, so I assume for the rest of this answer) this means sizeof(long) == 8 . On 32-bit machines, this means sizeof(long) == 4 .

int almost always 32 bits wide.

long long int often has a width of 64 bits.

+6
source

Are things like the number of bits in char or sizeof (int) processor dependencies OS dependent, compiler dependent or some combination above?

Compiler dependent. And your compiler is processor dependent and OS dependent on its own.

This means that if you compile a program on your PC, where int or void* has 4 bytes, and move the executable file to another computer, it cannot happen that it will be a different number of bytes. The compiler displays the machine code for a specific machine.

But if you compile the same source in another compiler or in the same version of the compiler, but for a different OS or in the same compiler, but with different settings, you may encounter changes.

For example, on my PC with 64-bit GCC, void* takes 8 bytes, but it compiles with -m32 , it takes 4 bytes.

+3
source

Well, this is the compiler that installs this data. And he does it according to the software / hardware information (e.g. processor or OS, as you said).

+2
source

Source: https://habr.com/ru/post/921072/


All Articles