Home > Backend Development > C++ > Why does the compiler allow self-initialization of variables in C/C ?

Why does the compiler allow self-initialization of variables in C/C ?

Susan Sarandon
Release: 2024-11-16 06:50:03
Original
587 people have browsed it

Why does the compiler allow self-initialization of variables in C/C  ?

Uninitialized Variables in Self-Initialization: Behavior and Standards

In the realm of programming, it is often a point of concern to use uninitialized variables. However, in the case of an uninitialized variable being used as its own initializer, a unique scenario arises.

Consider the following code:

int main(void) {
    int i = i;
}
Copy after login

Surprisingly, this code is It can be compiled with clang/gcc/clang /g using standards such as 11. Additionally, the compiler does not issue any warnings when you specify the -Wall -Wextra option.

However, if you change your code to int i = i 1; and specify the -Wall option, you may receive a warning similar to the following:

why.c:2:13: warning: variable 'i' is uninitialized when used within its own initialization [-Wuninitialized]
    int i = i + 1;
        ~   ^
1 warning generated.
Copy after login

So why does the compiler allow this code? Also, how does the C/C standard specify this?

Compiler Tolerance

The variable i is uninitialized when it self-initializes, so it has a non-specific value at that point. A non-specific value is either unspecified value or trap expression.

If an implementation supports stuffing bits for integer types and non-specific values ​​are trap expressions, using it will result in undefined behavior.

If the implementation does not have the integer padding bit, the value is simply unspecified and no undefined behavior occurs.

Standard Provisions

Section 6.3.2.1p2 of the C11 standard details:

lvalue represents an object with automatic storage duration, the object could have been declared with the register storage class (the address was never taken), and the object was uninitialized ( If it is not declared in an initializer and no assignment is performed before use), its behavior is undefined.

So if you have never obtained the address of i, you will get undefined behavior. Otherwise, the above statement applies.

The above is the detailed content of Why does the compiler allow self-initialization of variables in C/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