CS253: Software Development with C++

Spring 2018

Not Fully Specified

See this page as a slide show

CS253 Not Fully Specified

What the language definition does not say.

Different types of odd stuff

The C++ standard defines several kinds of not-fully specified things:

Implementation-defined (§1.9.2):

A choice made by the compiler, must be documented

Unspecified behavior (§1.9.3):

A choice made by the compiler, need not be documented

Undefined behavior (§1.9.4):

All bets are off!

Implementation-defined

A choice made by the compiler, which must be documented.

// Maximum value of a double:
double d = 6e307;
cout << d << '\n' << d*2 << '\n' << d*3;
6e+307
1.2e+308
inf
// Signed overflow:
short s = 32767;
cout << ++s;
-32768

Implementation-defined examples

// Character set used:
cout << "\x41\x53\x43\x49\x49\x0a";
ASCII
// Size of variables:
cout << sizeof(int) << '\n';
4
// Shifting a signed value right:
cout << (-1 >> 4) << '\n';
-1
// Calling system():
system("date");
Fri Nov 22 02:42:47 MST 2024

Unspecified

A choice made by the compiler, need not be documented or consistent.

// Comparing addresses of different objects:
int a,b;
cout << boolalpha << (&a < &b);
false
// Order of evaluation of an expression (mostly):

int foo() { cout << "foo\n"; return 0; }

int bar() { cout << "bar\n"; return 0; }

int main() {
    return foo()+bar();
}
foo
bar

Unspecified examples

// Order of evaluation of function arguments:
int foo() { cout << "foo\n"; return 1; }
int bar() { cout << "bar\n"; return 1; }

void ignore_arguments(int, int) { }

int main() {
    ignore_arguments(foo(), bar());
}
bar
foo

Undefined behavior

All bets are off! Anything can happen. Warnings are not required.

// Uninitialized value:
int a[135];
a[30] = 0;
cout << a[100] << '\n';
c.cc:4: warning: 'a[100]' is used uninitialized in this function
0
// Dereferencing a null pointer:
cout << "This HAS to be displayed!\n";
int *p = nullptr;
cout << *p << '\n';
SIGSEGV: Segmentation fault
// Shifting too far:
int amount=35;
cout << (1<<amount);
8

Undefined examples

// Multiple writes to the same location:
int a = 0;
cout << ++a + ++a;
c.cc:3: warning: operation on 'a' may be undefined
4
// Multiple writes to the same location:
int a=10;
cout << (a=20) * (a=30);
c.cc:3: warning: operation on 'a' may be undefined
900

But Why?

C++ is quite concerned about efficiency.

C++’s attitude is “You break the rules, you pay the price.” It doesn’t hold your hand.

User: Guest

Check: HTML CSS
Edit History Source

Modified: 2018-04-24T16:55

Apply to CSU | Contact CSU | Disclaimer | Equal Opportunity
Colorado State University, Fort Collins, CO 80523 USA
© 2018 Colorado State University
CS Building