xinaiz
xinaiz

Reputation: 7788

Variable initialization with itself

Is it safe to write such code?

#include <iostream>

int main()
{
    int x = x-x;// always 0
    int y = (y)? y/y : --y/y // always 1
}

I know there is undefined behaviour, but isn't it in this case just a trash value? If it is, then same value minus same is always 0, and same value divided by itself (excluding 0) is always 1. It's a great deal if one doesn't want to use integer literals, isn't it? (to feint the enemy)

Upvotes: 1

Views: 152

Answers (4)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385405

I know there is undefined behaviour, but isn't it in this case just a trash value? If it is, then same value minus same is always 0, and same value divided by itself (excluding 0) is always 1.

No! No, no, no!

The "trash value" is an "indeterminate value".

Subtracting an indeterminate value from itself does not yield zero: it causes your program to have undefined behaviour ([C++14: 8.5/12]).

You cannot rely on the normal rules of arithmetic to "cancel out" undefined behaviour.

Your program could travel back in time and spoil Game of Thrones/The Force Awakens/Supergirl for everyone. Please don't do this!

Upvotes: 8

Richard Hodges
Richard Hodges

Reputation: 69942

Allow me to demonstrate the evil magic of undefined behaviour:

given:

#include <iostream>

int main()
{
    using namespace std;
    int x = x-x;// always 0
    int y = (y)? y/y : --y/y; // always 1

    cout << x << ", " << y << endl;

    return 0;
}

apple clang, compile with -O3:

output:

1439098744, 0

Undefined is undefined. The comments in the above code are lies which will confound future maintainers of your random number generator ;-)

Upvotes: 8

hyde
hyde

Reputation: 62906

Undefined behavior is undefined behavior. There's no "isn't it in this case something specific" (unless you are actually talking about result of a completed compilation, and looking at the generated machine code, but that is no longer C++). Compiler is allowed to do whatever it pleases.

Upvotes: 1

Baum mit Augen
Baum mit Augen

Reputation: 50111

Undefined behavior is undefined. Always. Stuff may work or break more or less reliably on certain platforms, but in general, you can not rely on this program not crashing or any variable having a certain value.

Upvotes: 1

Related Questions