With C and C++ prefer use of int over char and short. The main reason behind this is that C and C++ perform arithmetic operations and parameter passing at integer level, If you have an integer value that can fit in a byte, you should still consider using an int to hold the number. If you use a char, the compiler will first convert the values into integer, perform the operations and then convert back the result to char.
Lets consider the following code which presents two functions that perform the same operation with char and int.
Compaing char and int operations
|
char sum_char(char a, char b)
{
char c;
c = a + b;
return c;
}
int sum_int(int a, int b)
{
int c;
c = a + b;
return c;
}
|
A call to sum_char involves the following operations:
- Convert the second parameter into an int by sign extension (C and C++ push parameters in reverse)
- Push the sign extended parameter on the stack as b.
- Convert the first parameter into an int by sign extension.
- Push the sign extended parameter on to the stack as a.
- The called function adds a and b
- The result is cast to a char.
- The result is stored in char c.
- c is again sign extended
- Sign extended c is copied into the return value register and function returns to caller.
- The caller now converts again from int to char.
- The result is stored.
A call to sum_int involves the following operations:
- Push int b on stack
- Push int a on stack
- Called function adds a and b
- Result is stored in int c
- c is copied into the return value register and function returns to caller.
- The called function stores the returned value.
Thus we can conclude that int should be used for all interger variables unless storage requirements force us to use a char or short. When char and short have to be used, consider the impact of byte alignment and ordering to see if you would really save space. (Many processors align structure elements at 16 byte boundaries)