Is there a relation between integer and register sizes?

c++, cpu, cpu-registers, integer, memory

Solution

The C++ standard doesn't specify the size of an int. (It says that `sizeof(char) == 1`, and `sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long)`.

So there doesn't have to be a relation to register size. A fully conforming C++ implementation could give you 256 byte integers on your PC with 32-bit registers. But it'd be inefficient.

So yes, in practice, the size of the `int` datatype is generally equal to the size of the CPU's general-purpose registers, since that is by far the most efficient option.

If an `int` was bigger than a register, then simple arithmetic operations would require more than one instruction, which would be costly. If they were smaller than a register, then loading and storing the values of a register would require the program to mask out the unused bits, to avoid overwriting other data. (That is why the `int` datatype is typically more efficient than `short`.)

(Some languages simply require an `int` to be 32-bit, in which case there is obviously no relation to register size --- other than that 32-bit is chosen because it is a common register size)

Problem

Recently, I was challenged in a recent interview with a string manipulation problem and asked to optimize for performance. I had to use an iterator to move back and forth between TCHAR characters (with UNICODE support - 2bytes each). Not really thinking of the array length, I made a curial mistake with not using size_t but an int to iterate through. I understand it is not compliant and not secure. ``` int i, size = _tcslen(str); for(i=0; i<size; i++){ // code here } ``` But, the maximum memory we can allocate is limited. And if there is a relation between int and register sizes, it may be safe to use an integer. E.g.: Without any virtual mapping tools, we can only map 2^register-size bytes. Since TCHAR is 2 bytes long, half of that number. For any system that has int as 32-bits, this is not going to be a problem even if you dont use an unsigned version of int. People with embedded background used to think of int as 16-bits, but memory size will be restricted on such a device. So I wonder if there is a architectural fine-tuning decision between integer and register sizes.

Original source