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

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

问题描述

我刚刚花了最后一天调试某些东西,最终使我最终冒犯了我.到达这条线的路径并不十分清楚,一旦我发现它,就会有一掌可怜的脸...

  int v = func(& v);//为什么允许我这样做. 

这是否不会生成某种在定义前使用过的变种"警告?令人讨厌的是,因为没有编译器错误或警告?当然,在语法:(下也没有红色下垂的线条.所以我跳过了它...

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

诚然,我对编译器复杂性的知识不是很好,所以我可能缺少一些显而易见的东西,但是在我看来,我就像在定义它之前就使用了var,可以说我在声明它之前就使用了它!/p>

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

解决方案

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

这在 C ++ 17 6.3.2声明点[basic.scope.pdecl] 部分(措辞如下)的第 1 段中进行了介绍:

名称的声明点紧接在其完整的声明器之后且在其初始值设定项(如果有)之前.

还有一个给出有效(尽管不是很聪明)代码的具体示例:

  unsigned char x = x; 

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?

解决方案

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;

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

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