C++ 语法错误,编译器不会对 int v = func(&v); 发出警告或错误 [英] Error with C++ syntax, compiler doesn't warn or error for int v = func(&v);

查看:25
本文介绍了C++ 语法错误,编译器不会对 int v = func(&v); 发出警告或错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在最后一天调试了一些东西,但最终我发现了一条有问题的线路.这条线的路径不是很清楚,我一看到它就有一个慢动作的手掌......

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.

这不应该产生某种定义前使用的变量"警告吗?这非常烦人,因为没有编译器错误或警告?当然,语法下没有红色 suiggly 线 :(.所以我直接跳过它...

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...

奇怪的是,它在大多数情况下都有效,直到被发现.. 我猜对 UB 很幸运?

oddly, it worked in most cases until it was spotted.. lucky with the UB I guess?

诚然,我对编译器复杂性的了解并不多,所以我可能遗漏了一些明显的东西,但在我看来,我只是在定义它之前使用了一个 var,可以说我在声明它之前使用了它!

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!

为什么这是有效的 C++ 语法?

Why is this valid C++ syntax?

推荐答案

变量名在其声明符出现后就在作用域内.代码不是未定义的行为本身;使用尚未初始化的变量的地址即可.

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.

这在 C++17 6.3.2 Point of Declaration [basic.scope.pdecl] 部分的第 1 段中有所介绍(释义):

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;

这篇关于C++ 语法错误,编译器不会对 int v = func(&v); 发出警告或错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆