Hello:
Can the following program generate an undefined behavior?
Thank you.
#include<limits.h>
int main()
{
#if INT_MAX == LONG_MAX
long getchar();
#else
int getchar();
#endif
(void) getchar();
return 0;
}
Programs do not generate undefined behavior. "undefined behavior" does
not mean a particular kind of behavior. It means that the behavior is
NOT defined - it can be anything. Code with undefined behavior is
perfectly capable of behaving in precisely the fashion you incorrectly
thought it was required to behave.
Section 7.1.4 says "Provided that a library function can be declared
without reference to any type defined in a header, it is also
permissible to declare the function and use it without including its
associated header.", so the declaration using 'int' is permissible.
However, 6.5.2.2p9 says " If the function is defined with a type that is
not compatible with the type (of the expression) pointed to by the
expression that denotes the called function, the behavior is
undefined."
A function declaration that is not a function prototype, and is used in
a function call expression with no arguments, can be compatible with a
function defined as taking no parameters - but only if the return types
are compatible. Nothing in the standard allows you to assume that 'long'
and 'int' are compatible types, not even if INT_MAX == LONG_MAX. 'int'
could be a one's complement type, while 'long' is a 2's complement type.
'int' could be little-endian, while 'long' could be big-endian. When
used as function arguments, 'int' and 'long' values could be passed in
different registers.
None of those possibilities is very likely. In all probability, your
code will work fine, particularly since it discards the return value,
unused. However, the fact that it will probably work is NOT guaranteed
by the standard, the correct wording to describe that absence of a
guarantee is "the behavior of your program is undefined".