Sujet : Re: int a = a (Was: Bart's Language)
De : david.brown (at) *nospam* hesbynett.no (David Brown)
Groupes : comp.lang.cDate : 18. Mar 2025, 20:51:44
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vrcisg$35ffo$1@dont-email.me>
References : 1 2 3 4 5
User-Agent : Mozilla Thunderbird
On 18/03/2025 19:04, Kenny McCormack wrote:
In article <vrc75b$2r4lt$1@dont-email.me>,
David Brown <david.brown@hesbynett.no> wrote:
...
gcc won't warn until you say '-Wextra', and then only for:
>
int a = a + 1;
>
People would not normally write "int a = a;". It is used as a common
idiom meaning "I know it is not clear to the compiler that the variable
is always initialised before use, but /I/ know it is - so disable the
use-without-initialisation warnings for this variable". So it makes
perfect sense for the compiler not to warn about it!
Wouldn't it just be easier and clearer to write: int a = 0;
and be done with it?
Write that if that's what you want.
I don't think I have ever actually written "int a = a;" in my own code - but I know the idiom. In almost all cases, I don't declare a variable until I have something to put in it, so I have a real initialiser. And if I don't, I prefer to leave it uninitialised - then the compiler can tell me if I haven't initialised it when I use it. "int a = a;" would only be useful in fairly niche cases.
"int a = a + 1;", on the other hand, clearly attempts to read the value
of "a" before it is initialised, and a warning is issued if
"-Wuninitialized" is enabled. This warning is part of "-Wall".
How is: int a = a + 1;
conceptually different from: int a = a;
Both are expressions involving 'a'.
Isn't 'a' being used un-initialised in both cases?
The case "int a = a;" is recognised as an idiom by a number of compilers (such as gcc). A brief check suggests that gcc will generate code as it would for "int a = 0;", but it is certainly possible for a compiler to avoid any kind of initialisation here and let the register or stack slot used for "a" stay as it was. That would be a pretty minor efficiency improvement, but optimised code is mostly the sum of lots of tiny improvements.
(You have to know the value of 'a' in order to evaluate the expression: a)