问题
I've just spent the last day debugging something in which I ultimately ended up on an offending line. The path to this line wasn't exactly clear, and there was a slo-mo face palm once I spotted it...
int v = func(&v); // why am I allowed to do this.
Should this not generate some sort of 'var used before defined' warning? It was incredibly annoying because there was no compiler error or warning? and of course, no red suiggly line under the syntax :(. So I skipped right over it...
oddly, it worked in most cases until it was spotted.. lucky with the UB I guess?
Admitedly, my knowledge of compiler intricacies isn't great, so I am probably missing something obvious, but it looks to me like I just used a var before defining it, it could be argued I used it before declaring it!
Why is this valid C++ syntax?
回答1:
A variable name is in scope as soon as its declarator has appeared. The code is not undefined behaviour per se; it is fine to use the address of a variable that has not yet been initialized.
This is covered in the paragraph 1
of the C++17 6.3.2 Point of declaration [basic.scope.pdecl]
section (paraphrased):
The point of declaration for a name is immediately after its complete declarator and before its initializer (if any).
There's also a specific example given there of valid (albeit not very smart) code:
unsigned char x = x;
来源:https://stackoverflow.com/questions/51052610/error-with-c-syntax-compiler-doesnt-warn-or-error-for-int-v-funcv