06 August 2011

Why C accept confusion in conditional operation while Java not

Usually, when we begun to learn Programming in C, our teachers warn us from the following Syntax:

if ( i = 30)

They said that, we have to beware cause it will lead to logical error rather thank syntax error.. ( it will be translated to if (30) )

But when we looked in higher langs like Java/C#, we found that, the compiler will issue a compilation error if he find such statement.

The difference appears because, in C/C++ there were originally bool datatype, so expressions were evaluated to zero and none-zero.
Zero for false, and non-zero for true.

So, the statement:
if (i = 30 )
Will always translated to if (30) which is a valid C/C++ statement that it understand as it were: if (true)

But in Java, relational expressions are only evaluated to Boolean types which is a completely separate type, which takes only two values, constant true and constant false.. so such statement will be always syntactically incorrect.

BTW, I could say that the following is the C implementation of true and false constants (implemented as macros):

#define FALSE 0
#define TRUE !FALSE
Post a Comment