开发者

Why syntax error occurs when a void function is checked in IF statement

开发者 https://www.devze.com 2023-01-07 15:57 出处:网络
What will be the output if I write In开发者_如何学Python C++ if(5) will be executed without any problem but not in C# same way will it be able to run.

What will be the output if I write

In开发者_如何学Python 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


In C# the type of the condition in an if statement has to be implicitly convertible to bool. This reduces errors in various situations, and is basically a Good Thing. It prevents things like this from compiling:

int x = ...;
if (x = 10) // Valid in C / C++, not in C#

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...


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.


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.


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) { ... }


In C and C++ there is an implicit conversion of int , pointers and most other types to bool.

The designers of C# elected not to have that, for clarity.

So with

int i = 1;
int* P = null;

if (i && p) { } // OK in C++

if (i != 0 && p != null) { }  // OK in C++ and C#
0

精彩评论

暂无评论...
验证码 换一张
取 消