The C language standard precisely specifies theobservable behavior of C language programs, except for the ones in the following categories:
(Note:Strictly conforming programs do not depend on any unspecified, undefined, or implementation-defined behavior)
The compilers are required to issue diagnostic messages (either errors or warnings) for any programs that violates any C syntax rule or semantic constraint, even if its behavior is specified as undefined or implementation-defined or if the compiler provides a language extension that allows it to accept such program. Diagnostics for undefined behavior are not otherwise required.
Contents |
Because correct C programs are free of undefined behavior, compilers may produce unexpected results when a program that actually has UB is compiled with optimization enabled:
For example,
int foo(int x){return x+1> x;// either true or UB due to signed overflow}
may be compiled as (demo)
foo: mov eax,1 ret
int table[4]={0};int exists_in_table(int v){// return 1 in one of the first 4 iterations or UB due to out-of-bounds accessfor(int i=0; i<=4; i++)if(table[i]== v)return1;return0;}
May be compiled as (demo)
exists_in_table: mov eax,1 ret
May produce the following output (observed with an older version of gcc):
p istruep isfalse
May be compiled as (demo)
f: mov eax,42 ret
int f(void){ _Bool b=0;unsignedchar* p=(unsignedchar*)&b;*p=10;// reading from b is now UBreturn b==0;}
May be compiled as (demo)
f: mov eax,11 ret
int foo(int* p){int x=*p;if(!p)return x;// Either UB above or this branch is never takenelsereturn0;} int bar(){int* p=NULL;return*p;// Unconditional UB}
may be compiled as (demo)
foo: xor eax, eax retbar: ret
Choose clang to observe the output shown
Possible output:
12
Choose clang to observe the output shown
#include <stdio.h> int fermat(){constint MAX=1000;// Endless loop with no side effects is UBfor(int a=1, b=1, c=1;1;){if(((a* a* a)==((b* b* b)+(c* c* c))))return1;++a;if(a> MAX){ a=1;++b;}if(b> MAX){ b=1;++c;}if(c> MAX) c=1;}return0;} int main(void){if(fermat())puts("Fermat's Last Theorem has been disproved.");elseputs("Fermat's Last Theorem has not been disproved.");}
Possible output:
Fermat's Last Theorem has been disproved.
C++ documentation forUndefined behavior |