Home > Backend Development > C++ > body text

Why Does `i = i ` Lead to Undefined Behaviour in C ?

Patricia Arquette
Release: 2024-10-25 09:07:29
Original
368 people have browsed it

Why Does `i = i  ` Lead to Undefined Behaviour in C  ?

The Undefined Behaviour of i = i

The C Standard defines "undefined behaviour" as behaviour that is not explicitly specified by the standard. This means that the compiler is free to generate any code it wants when encountering undefined behaviour, even if it results in unpredictable or erroneous output.

One example of undefined behaviour is the assignment of a value to a variable that is about to be modified. Consider the following code snippet:

<code class="cpp">i = 3;
i = i++;</code>
Copy after login

According to the standard, this code will result in undefined behaviour. However, it is often assumed that the final value of i will be 4, regardless of the order of evaluation. This is not necessarily true.

The compiler could emit code that is equivalent to any of the following:

<code class="cpp">i = 3;
int tmp = i;
++i;
i = tmp;

i = 3;
++i;
i = i - 1;

i = 3;
i = i;
++i;</code>
Copy after login

In the first two cases, the final value of i will be 4. However, in the third case, the final value of i will be 3.

Therefore, it is incorrect to assume that the final value of i will always be 4. The actual behaviour is undefined and compiler-dependent.

As a general rule, it is best to avoid undefined behaviour. If you encounter code that exhibits undefined behaviour, it is important to fix it as soon as possible.

The above is the detailed content of Why Does `i = i ` Lead to Undefined Behaviour in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template