6.5 — Variable shadowing (name hiding) | Learn C++ https://www.learncpp.com/cpp-tutorial/variable-shadowing-name-hiding/

Go的50度灰:Golang新开发者要注意的陷阱和常见错误 | 鸟窝 https://colobu.com/2015/09/07/gotchas-and-common-mistakes-in-go-golang/

6.5 — Variable shadowing (name hiding)

BY ALEX ON JANUARY 3RD, 2020 | LAST MODIFIED BY NASCARDRIVER ON APRIL 25TH, 2020

Each block defines its own scope region. So what happens when we have a variable inside a nested block that has the same name as a variable in an outer block? When this happens, the nested variable “hides” the outer variable in areas where they are both in scope. This is called name hiding or shadowing.

Shadowing of local variables

#include <iostream>

int main()
{ // outer block
int apples { 5 }; // here's the outer block apples { // nested block
// apples refers to outer block apples here
std::cout << apples << '\n'; // print value of outer block apples int apples{ 0 }; // define apples in the scope of the nested block // apples now refers to the nested block apples
// the outer block apples is temporarily hidden apples = 10; // this assigns value 10 to nested block apples, not outer block apples std::cout << apples << '\n'; // print value of nested block apples
} // nested block apples destroyed std::cout << apples << '\n'; // prints value of outer block apples return 0;
} // outer block apples destroyed

  

If you run this program, it prints:

5
10
5

In the above program, we first declare a variable named apples in the outer block. This variable is visible within the inner block, which we can see by printing its value (5). Then we declare a different variable (also named apples) in the nested block. From this point to the end of the block, the name apples refers to the nested block apples, not the outer block apples.

Thus, when we assign value 10 to apples, we’re assigning it to the nested block apples. After printing this value (10), nested block apples is destroyed. The existence and value of outer block apples is not affected, and we prove this by printing the value of outer block apples (5).

Note that if the nested block apples had not been defined, the name apples in the nested block would still refer to the outer block apples, so the assignment of value 10 to apples would have applied to the outer block apples:

#include <iostream>

int main()
{ // outer block
int apples{5}; // here's the outer block apples { // nested block
// apples refers to outer block apples here
std::cout << apples << '\n'; // print value of outer block apples // no inner block apples defined in this example apples = 10; // this applies to outer block apples std::cout << apples << '\n'; // print value of outer block apples
} // outer block apples retains its value even after we leave the nested block std::cout << apples << '\n'; // prints value of outer block apples return 0;
} // outer block apples destroyed

  

The above program prints:

5
10
10

When inside the nested block, there’s no way to directly access the shadowed variable from the outer block.

Shadowing of global variables

Similar to how variables in a nested block can shadow variables in an outer block, local variables with the same name as a global variable will shadow the global variable wherever the local variable is in scope:

#include <iostream>
int value { 5 }; // global variable void foo()
{
std::cout << "global variable value: " << value << '\n'; // value is not shadowed here, so this refers to the global value
} int main()
{
int value { 7 }; // hides the global variable value until the end of this block ++value; // increments local value, not global value std::cout << "local variable value: " << value << '\n'; foo(); return 0;
} // local value is destroyed

  

This code prints:

local variable value: 8
global variable value: 5

However, because global variables are part of the global namespace, we can use the scope operator (::) with no prefix to tell the compiler we mean the global variable instead of the local variable.

#include <iostream>
int value { 5 }; // global variable int main()
{
int value { 7 }; // hides the global variable value
++value; // increments local value, not global value --(::value); // decrements global value, not local value (parenthesis added for readability) std::cout << "local variable value: " << value << '\n';
std::cout << "global variable value: " << ::value << '\n'; return 0;
} // local value is destroyed

  

This code prints:

local variable value: 8
global variable value: 4

Avoid variable shadowing

Shadowing of local variables should generally be avoided, as it can lead to inadvertent errors where the wrong variable is used or modified. Some compilers will issue a warning when a variable is shadowed.

For the same reason that we recommend avoiding shadowing local variables, we recommend avoiding shadowing global variables as well. This is trivially avoidable if all of your global names use a “g_” prefix.

Best practice

Avoid variable shadowing.

Go的50度灰:Golang新开发者要注意的陷阱和常见错误 | 鸟窝 https://colobu.com/2015/09/07/gotchas-and-common-mistakes-in-go-golang/

然的变量隐藏Accidental Variable Shadowing

短式变量声明的语法如此的方便(尤其对于那些使用过动态语言的开发者而言),很容易让人把它当成一个正常的分配操作。如果你在一个新的代码块中犯了这个错误,将不会出现编译错误,但你的应用将不会做你所期望的事情。

package main
import "fmt"
func main() {
x := 1
fmt.Println(x) //prints 1
{
fmt.Println(x) //prints 1
x := 2
fmt.Println(x) //prints 2
}
fmt.Println(x) //prints 1 (bad if you need 2)
}

  

即使对于经验丰富的Go开发者而言,这也是一个非常常见的陷阱。这个坑很容易挖,但又很难发现。

你可以使用 vet命令来发现一些这样的问题。 默认情况下, vet不会执行这样的检查,你需要设置-shadow参数:
go tool vet -shadow your_file.go

变量隐藏Accidental Variable Shadowing的更多相关文章

  1. Codeforces Gym 100513M M. Variable Shadowing 暴力

    M. Variable Shadowing Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/gym/100513/ ...

  2. R如何检验类别变量(nominal variable)与其他变量之间的相关性

    1.使用Pearson积差相关系性进行检验的话可以判断两个变量之间的相关性是否显著以及相关性的强度 显著性检验 (significant test) 连续变量 vs 类别变量 (continuous ...

  3. Go语言规格说明书 之 变量声明(Variable/Short variable declarations)

    go version go1.11 windows/amd64 本文为阅读Go语言中文官网的规则说明书(https://golang.google.cn/ref/spec)而做的笔记,完整的介绍Go语 ...

  4. c++并发编程之条件变量(Condition Variable)

    条件变量(Condition Variable)的一般用法是:线程 A 等待某个条件并挂起,直到线程 B 设置了这个条件,并通知条件变量,然后线程 A 被唤醒.经典的「生产者-消费者」问题就可以用条件 ...

  5. tensorflow变量作用域(variable scope)

    举例说明 TensorFlow中的变量一般就是模型的参数.当模型复杂的时候共享变量会无比复杂. 官网给了一个case,当创建两层卷积的过滤器时,每输入一次图片就会创建一次过滤器对应的变量,但是我们希望 ...

  6. Oracle 变量 之 define variable declare 用法及区别

    Oracle 变量 之 define variable declare 用法及区别 Table of Contents 1. 扯蛋 2. define和accept 3. variable 3.1. ...

  7. CMake语法—缓存变量(Cache Variable)

    目录 CMake语法-缓存变量(Cache Variable) 1 CMake缓存变量 2 定义缓存变量 2.1 定义格式 2.2 定义示例代码 2.3 运行结果 2.4 小结 3 CMakeCach ...

  8. CMake语法—环境变量(Environment Variable)

    目录 CMake语法-环境变量(Environment Variable) 1 定义环境变量 2 应用环境变量 2.1 代码结构 2.2 示例代码 2.3 运行结果 3 小结 CMake语法-环境变量 ...

  9. 引人瞩目的 CSS 变量(CSS Variable)

    这是一个令人激动的革新. CSS 变量,顾名思义,也就是由网页的作者或用户定义的实体,用来指定文档中的特定变量. 更准确的说法,应该称之为 CSS 自定义属性 ,不过下文为了好理解都称之为 CSS 变 ...

随机推荐

  1. IQueryable的简单封装

    IQueryable的简单封装 前言 前两天在园子上看到一个问题 半年前我也考虑过这些问题,但由于这样那样的问题,没有尝试去解决. 后来公司用上了 abp vnext ,然后有一部分代码可以这样写 p ...

  2. maven项目修改名称后,打包名称和现在名称不一致

    将pom.xm文件中 <artifactId>health</artifactId> 修改成现在项目名称,然后 maven clean ->maven install 如 ...

  3. 使用maven创建java项目是,jdk的版本默认为1.5,如何修改为1.8

    <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> ...

  4. [leetcode]罗马数字和阿拉伯数字相互转换

    罗马转阿拉伯 public int romanToInt(String s) { /* 从左到右依次根据哈希表进行加法 如果是"CM"900这种情况就要执行+M和-C处理 */ i ...

  5. Idea创建Maven项目时出现Failed to execute goal org.apache.maven.plugins:maven-archetype-plugin:3.0.1错误

    如果Maven中用的jre用的是idea中自带的,但是环境变量JAVA_HOME配置的是自己的jdk,那么就会出现 解决方法是到settiing中把jre改成自己的jdk中的jre 经过尝试,问题解决

  6. js实现页面消息滚动效果

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  7. jsonp详解及跨域请求

    什么是JSONP? JSON是一种轻量级的数据传输格式语言,被广泛应用于当前Web应用中.JSON格式数据的编码和解析基本在所有主流语言中都被实现,所以现在大部分前后端分离的架构都以JSON格式进行数 ...

  8. WebService 适用场合

    适用场合 1.跨防火墙通信 如果应用程序有成千上万的用户,而且分布在世界各地,那么客户端和服务器之间的通信将是一个棘手的问题.因为客户端和服务器之间通常会有防火墙或者代理服 务器.在这种情况下,使用D ...

  9. 在Docker下进行MyCAT管理双主双从MySQL集群

    前言 在Docker下双主双从MySQL集群模拟 https://www.cnblogs.com/yumq/p/14259964.html 本文实验配置文件 Docker拉取MyCAT镜像 如果没启动 ...

  10. OOP、封装、继承、多态,真的懂了吗?

    平时只要一提起来面向对象编程OOP的好处,随口就能说出来,不就是封装.继承.多态么,可他们的含义是什么呢,怎么体现,又有什么非用不可的好处啊.可能平时工作中天天在用OOP,仅仅是在用OOP语言,就是一 ...