简体   繁体   English

如果未初始化int,会发生什么?

[英]What happens to an int if it's not initilized?

I found this question, and whenever I try to run it, it gives me an error that it could not compile because the variable r has not been initialized. 我找到了这个问题,每当我尝试运行它时,都会出现错误,因为变量r尚未初始化,因此无法编译。 This is the question.... 这是问题。

int n=1; int k=2; int r;
if(k<r) {
  r=n;
}

"What is the value of each variable after the if statement?" “ if语句之后的每个变量的值是多少?”

You've already answered the question. 您已经回答了问题。 The code doesn't compile. 该代码无法编译。 Unlike when used as a class member local primitive types do not have a default value. 与用作类成员时不同,本地基本类型没有默认值。 And since it doesn't compile it can't execute. 而且由于它不编译,因此无法执行。

Since the code can't pass compilation, the if statement is never executed. 由于代码无法通过编译,因此永远不会执行if语句。 Nothing is executed, so none of the variables have values. 不执行任何操作,因此所有变量都没有值。

When an int is not initialized or generally when a variable is not initialized (other than static methods/fields in classes) it cannot be used. 当未初始化int或通常未初始化变量(类中的静态方法/字段除外)时,将无法使用它。 You can have a variable like int x; 你可以有一个像int x这样的变量。 and compile a program where x is not initialized BUT not used as well, in this case it will work 并编译一个未初始化x但未使用x的程序,在这种情况下它将起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM