-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hi,
I'm reading about int promotion: char and short shoud be avoided
because are changed in int variables during arithmetic operations...So
i shoud always avoid char and short variables? These variables are
smaller in byte size, but new instructions (like sign extending) are
implemented at compiler time: these instructions occupy memory bytes
so (apparently) there is no advantage to use short data type....or
not?
For arithmetic operation, everything less than an `int' is converted to
either `int' or `unsigned int', depending whether the source type is a
subset of `int'. In theory, these operation should be performed on type
`int' but an optimizing compiler can omit these conversions when
appropriate.
Consider the following header:
size_t printf(const char *fmt, ...);
When passing `char's and `short's to the variable arguments part, they will
be promoted to `int's prior to passing. Therefore, when you try to read the
arguments, you need to take an `int' out when a `char' or `short' is
expected. Similar for `float' and `double'. However, This promotion does not
occur when a function prototype is in effect. Instead, the argument is
convert to the type of the function prototype.
Consider the following pair of old-style function declaration and definition
(very old K&R C without the void keyword):
main(argc, argv)
int argc;
char **argv;
{
unsigned char x = 0;
foo(x); /* foo is implicitly declared as `int foo(...)' */
return 0;
}
foo(n)
unsigned char n;
{
// blah
}
Here, n is converted from a `unsigned char' to an `int' (possibly `unsigned
int' if `char' is the same size of `int') in main(), passed into foo, and
converted back to `unsigned char'. To modify the declaration into prototype
form, you should write this (standard C90):
int foo(int);
int main()
int argc;
char **argv;
{
unsigned char x = 0;
foo(x);
return 0;
}
int foo(n)
unsigned char n;
{
// blah
}
Later, to convert the definition to prototype form:
int foo(int);
int main(int argc, char **argv)
{
unsigned char x = 0;
foo(x);
return 0;
}
int foo(int _n)
{
unsigned char n = _n;
// blah
}
In general, although some CPU does provide byte/short operation directly, it
is better not using them unless memory is very tight.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)
iEYEARECAAYFAks3Z0kACgkQG6NzcAXitM+rIQCfSPqKhya1RWQCIppE/+px4+pw
AjwAnAvwS0SyKAjCTP0V3J3QqqMc+CxK
=638p
-----END PGP SIGNATURE-----