再次声明变量时可以随机设置变量吗? [英] can variables be set randomly when declaring them again?

查看:87
本文介绍了再次声明变量时可以随机设置变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的方法中,我声明了一些变量,包括int blockCount;.我多次调用此方法.使用Xcode调试器,我发现第二次调用该方法后,blockCount的值设置为364265,而将其设置为2,仅几毫秒前.

In my method, I declare some variables, including int blockCount;. I call this method more than once. Using the Xcode debugger, I found out that after the second time the method was called, the value of blockCount was set to 364265, while it was set to 2, just a few milliseconds earlier.

这不是一个真正的问题,因为我可以将其设置为0或我想要的任何其他数字,但是重复声明某个变量是否是不良的编程习惯?我对编程还很陌生,所以我想确保自己以正确的方式做事. :)

It's not a real problem, since I can just set it to 0 or any other number I'd like, but is it bad programming habit to have a certain variable declared over and over again? I'm quite new to programming, and I want to make sure I'm doing things the right way. :)

推荐答案

如果您声明了变量但未提供值,则将其视为未初始化". C语言中未初始化的变量具有未定义"的值-通常是垃圾,包含上次在此处写入内容时在该地址发生的任何事情.但是严格来说,未定义"表示您在任何情况下都不应尝试使用该值. (如果您搜索鼻恶魔",将会以非常丰富多彩且有用的术语进行解释.*)

If you declare a variable but don't provide a value for it, it is considered "uninitialized". An uninitialized variable in C has an "undefined" value -- it's usually garbage, containing whatever happened to be at that address the last time something was written there. Strictly speaking, though, "undefined" means that you should under no circumstances try to use that value. (If you do a search for "nasal demons" this will be explained in quite colorful, and also useful, terms.*)

该变量是局部变量,每次运行该方法时都会重新创建,因此会获得一个新的 actual ,尽管每次传递都在技术上仍 undefined .

This variable, being local, is recreated every time the method runs, and thus gets a new actual, though still technically undefined value each pass.

通常建议不要将变量保留为未初始化状态,因为"random"值可能会导致难以发现的错误,并偶尔会召唤上述鼻恶魔.您没有做错任何事情,但是如果您未在声明的两行中设置实际值,建议将其初始化为0或一些合理的默认值:

It's generally recommended to not leave variables uninitialized, because the "random" value can cause bugs that are hard to find, and occasionally summon the aforementioned nasal demons. You're not doing anything wrong, but if you're not setting the actual value within a line or two of the declaration, I'd suggest initializing it to 0 or some sensible default:

int blockCount = 0;


*另请参见: 查看全文

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