Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'Conditional expressions can be only boolean, not integral.' mean?

What does 'Conditional expressions can be only boolean, not integral.' mean? I do not know Java and I know C++ deffenetly not enought to understend what it means.. Please help (found in http://www.javacoffeebreak.com/articles/thinkinginjava/comparingc++andjava.html in Comparing C++ and Java item 7 sub item 1)

like image 404
Rella Avatar asked Nov 28 '22 15:11

Rella


2 Answers

It means you need a boolean for a conditional, a conversion from an integral type won't be implicit. Instead of if (x) you'd need if (x != 0), etc.

The former is an int which will be implicitly converted to bool in C++ (via != 0), but the latter expression yields a boolean directly.

like image 131
GManNickG Avatar answered Dec 18 '22 08:12

GManNickG


Conditional expressions are used by the conditional and loop control structures to determine the control flow of a program.

// conditional control structure
if (conditionalExpression) {
    codeThatRunsIfConditionalExpressionIsTrue();
} else {
    codeThatRunsIfConditionalExpressionIsFalse();
}

// basic loop control structure
while (conditionalExpression) {
    codeThatRunsUntilConditionalExpressionIsFalse();
}

// run-at-least-once loop control structure
do {
    codeThatRunsAtLeastOnceUntilConditionalExpressionIsFalse();
} while (conditionalExpression);

From a logical point of view, conditional expressions are inherently boolean (true or false). However, some languages like C and C++ allow you to use numerical expressions or even pointers as conditional expressions. When a non-boolean expression is used as a conditional expression, they are implicitly converted into comparisions with zero. For example, you could write:

if (numericalExpression) {
    // ...
}

And it would mean this:

if (numericalExpression != 0) {
    // ...
}

This allows for concise code, especially in pointer languages like C and C++, where testing for null pointers is quite common. However, making your code concise doesn't necessarily make it clearer. In high-level languages like C# or Java, using numerical expressions as conditional expressions is not allowed. If you want to test whether a reference to an object has been initialized, you must write:

if (myObject != null) /* (myObject) alone not allowed */ {
    // ...
}

Likewise, if you want to test whether a numeric expression is zero, you must write:

if (numericalExpression != 0) /* (numericalExpression) alone not allowed */ {
    // ...
}
like image 30
pyon Avatar answered Dec 18 '22 09:12

pyon