Search code examples
c#c++castingvoidconceptual

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


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


Solution

  • 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#