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)
What does 'Conditional expressions can be only boolean, not integral.' mean?
3.2k views Asked by Rella At
9
There are 9 answers
0
On
Take the statement:
if (a > b) {
// Do stuff
}
The "conditional expression" is a > b. In C++ you can do things like
int i = foo();
if (i) {
// do stuff
}
This is because integral (integer values) are treated as false when 0 and true otherwise. Languages like Java do not allow you to treat integers as boolean values in this way.
0
On
An expression is code that computes a value. In both languages an expression has a static type that described the kind of values this expression yields. Integral means the the expression's type is int.
Simply put, the authors emphasize each of the following is legal C++ code, but not legal Java code, because the if's expression yields an integer:
if (32) {
}
if (2 * 17 - 33) {
}
int c;
if (c = 12) {
}
Conditional expressions are used by the conditional and loop control structures to determine the control flow of a program.
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:
And it would mean this:
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:
Likewise, if you want to test whether a numeric expression is zero, you must write: