ISourceCode

Make the frequent cases fast and the rare case correct

Monthly Archives: March 2012

While loop execution in C and C# – subtle difference

while(int) would not compile in C# and would throw an error and say that the “Cannot implicitly convert type ‘int’ to ‘bool’” . In C# the while loop must strictly have a boolean expression evaluated or while(true) would work fine.

C# doesn’t allow you to use a number as a boolean, even though it’s allowed in C and C++ (where truth is nonzero and falsehood is zero)

some related discussion on stackoverflow.

#include <stdio.h>

void main()
{
        int i = 10;
        while (i)
        {
                printf("\n%d",i);
                i--;
        }
}

> ./a.out

10
9
8
7
6
5
4
3
2
1>

Follow

Get every new post delivered to your Inbox.