为什么在 IF 语句中检查 void 函数时会出现语法错误
输出将会是什么
如果我在 C++ 中编写 if(5)
将毫无问题地执行,但在 C# 中不会以同样的方式运行,那么
if(func()){} //in C# it doesn't runs Why how does C# treats void and how in Turbo C++
void func()
{
return;
}
if(null==null){}//runs in C#
。 编辑
if(printf("Hi"){} //will run and enter into if statement
if(printf(""){}//will enter into else condition if found.
这个问题不适合那些不了解 Turbo Compiler 的人
What will be the output if I write
In C++ if(5)
will be executed without any problem but not in C# same way will it be able to run.
if(func()){} //in C# it doesn't runs Why how does C# treats void and how in Turbo C++
void func()
{
return;
}
if(null==null){}//runs in C#
EDIT
if(printf("Hi"){} //will run and enter into if statement
if(printf(""){}//will enter into else condition if found.
This Question is not meant for those who are not aware of Turbo Compiler
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在 C# 中,
if
语句中的条件类型必须隐式转换为bool
。这减少了各种情况下的错误,基本上是一件好事。它会阻止这样的事情编译:即使在 C 和 C++ 中,如果您有合理的警告级别,一个像样的编译器也会在上面的行中向您发出警告。
如果
void
版本能在 C++ 中工作,我会感到惊讶......In C# the type of the condition in an
if
statement has to be implicitly convertible tobool
. This reduces errors in various situations, and is basically a Good Thing. It prevents things like this from compiling:Even in C and C++, a decent compiler will warn you on the above line though, if you have a sensible level of warnings.
I'm surprised if the
void
version works in C++ though...与 C/C++ 不同,C# 条件只能应用于布尔值。
请注意,void 函数没有返回值,因此不能对其应用任何条件。
Unlike C/C++, C# conditions can only be applied to Boolean values.
Note that void function does not have return value so no condition can be applied to it.
void 函数根本不返回任何内容,因此无法使用 if 语句检查其返回值。
即使 C++ 也不会让你这样做。
A void function does not return anything at all, thus its return value can not be checked with an if statement.
Even C++ wont let you do that.
在 C/C++ 中,非零整数值与逻辑 true 相同。原因是C/C++没有定义布尔类型,所以使用整数作为布尔变量。
后来,人们发现,当编译器试图找到函数的适当重载版本时,这种隐式类型转换会导致意外行为,因此在 C# 中没有重复这个错误。
要在 C# 中获得相同的行为,请编写
if (x!=0) { ... }
in C/C++, a nonzero integer value is the same as logical true. The reason for this is that C/C++ did not have a boolean type defined, so integers were used as boolean variables.
Later, people found out that this kind of implicit type conversion can cause unexpected behavior when the compiler tries to find the appropriate overloaded version of the function, therefore the mistake was not repeated in C#.
To get the same behavior in C#, write
if (x!=0) { ... }
在 C 和 C++ 中,
int
、指针和大多数其他类型都会隐式转换为bool
。为了清楚起见,C# 的设计者选择不这样做。
所以与
In C and C++ there is an implicit conversion of
int
, pointers and most other types tobool
.The designers of C# elected not to have that, for clarity.
So with