By Michael Gazonda

2014-07-17 20:45:34 8 Comments

In C++, there are things that come up that are somewhere between well-defined and undefined. Specifically, those are called implementation defined and unspecified. Right now, I'm interested in the unspecified stuff.

When is it okay to use such features, and when should they be avoided? Are there good examples of unspecified behaviour being a part of correct code? When, if ever, is it the best choice to make when writing software?

Definitions provided by Matt McNabb:

  • Undefined - anything at all can happen

  • Implementation-defined - a finite number of results are possible, and the compiler's documentation must say what happens

  • Unspecified - a finite number of results are possible -- usually the Standard describes the set of possible results

  • Well-defined - none of the above

  • Well-formed program - program that compiles without error (may exhibit undefined behaviour)

Follow-up question:

Do relaxed atomics count as unspecified or well-defined?

Marked as a duplicate of a question that talks about the same idea from a different perspective. The question marked as the same talks about the definition of unspecified behaviour, whereas here the question is about how and when to use it.


@M.M 2014-07-17 22:44:54

To answer the new question, "When is it OK to use unspecified behaviour?"

It may sound slightly facetious, but "any time it doesn't matter to you which option happens".

For example,

int foo() { cout << "foo"; return 1; }
int bar() { cout << "bar"; return 2; }
// ...
cout << (foo() + bar()) << "\n";

If you don't care whether you see "foobar3" or "barfoo3" then you could write this code. If it does matter then you would have to change it, e.g.

int i = foo(); i += bar(); cout << i << "\n";

The order is unspecified because it's good to leave freedom for the compiler to choose whichever order is optimal, in a more general case.

@Michael Gazonda 2014-07-17 23:29:44

"Any time it doesn't matter to you which option happens." Awesome! I want to explore that further.

Related Questions

Sponsored Content

17 Answered Questions

[SOLVED] When to use virtual destructors?

13 Answered Questions

[SOLVED] What is a smart pointer and when should I use one?

9 Answered Questions

8 Answered Questions

15 Answered Questions

[SOLVED] Purpose of Unions in C and C++

24 Answered Questions

[SOLVED] Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

1 Answered Questions

Sponsored Content