Philip Potter wrote:
I have a somewhat flippant question regarding undefined behaviour. Does
an operation which invokes undefined behaviour affect the whole program,
or are earlier statements guaranteed to execute correctly?
For example:
#include <stdio.h>
int main(void) {
int i;
printf("Hello, world!\n");
fflush(stdout);
i = i++; /* or some other undefined behaviour */
return 0;
}
Is the printf() statement guaranteed to execute? Is "Hello, world!\n"
guaranteed to be sent to stdout? Or could a conforming implementation
refuse to compile this program, or accept it and let loose nasal demons
without even greeting the world first?
Hard to say. Note that fflush() delivers any buffered
output "to the host environment," which may not be the same
thing as "to its final destination" -- which might, for
example, be on the far end of a TCP/IP connection currently
undergoing a network storm. fflush() will probably deliver
the data to the network stack and not wait for acknowledgment
from the other end, and then when the U.B. strikes and takes
the local machine down in flames, the remote side's socket
may just time out and give up. No greeting is received.
Also, there are undefined behaviors that are less strongly
tied to a particular execution path. For example,
/* main.c */
#include <stdio.h>
int answer = 42;
int function(void);
int main(void) {
printf ("%d\n", answer == 0 ? function() : answer);
return 0;
}
/* function.c */
extern double answer;
int function(void) { return answer; }
.... produces undefined behavior because the two declarations of
`answer' are in conflict (6.2.7p2). It's U.B. even though function()
is not called -- maybe the linker catches the mismatch and refuses
to produce an executable program, maybe the linker succeeds but
the program's frammis mapping is whirligigged, ...
--
Eric Sosman
es*****@ieee-dot-org.invalid