Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Newbie: Problem with "if" statement compatibility

Status
Not open for further replies.

LoserAndFailure

Programmer
Jan 27, 2005
4
US
Here is the fragment of code that the compiler keeps fussing about:

private int firstEmptyElement()
{
int i;

for (i=0; i<asciiRange.length; i++)
{
if (asciiRange = 0)
break;
}
return i;
}

And here is the error msg I get:


C:\jdk1.2.1\bin>javac PwGenerator.java
PwGenerator.java:152: Incompatible type for if. Can't convert int to boolean.
if (asciiRange = 0)
^
1 error

I'm like, "Excuse me???? I'm just checking to see if a certain value is zero or not and it's fussing at me about freakin' conversions from int to boolean?????" Why am I getting this error? I tried doing if(asciiRange = null), but I got an additional error. Your help will be greatly appreciated by this novice.

Baffled in the USA
 
As long as asciiRange is an array of ints, you should do :

if (asciiRange == 0) {
break;
}

You are missing an equals sign ...

--------------------------------------------------
Free Database Connection Pooling Software
 
'==' is a comparison, '=' is assignment. What's actually happening is that asciiRange will be set to 0, then the compiler tries to cast the resulting int to a boolean to satisfy the if. But it can't and that's what it's complaining about.

Easy mistake, and one I'm sure we've all made at some time or another...
 
If you tried the same code in C++, it'd actually compile... But, it would do the assignment and the if would always fail. This is one of those errors that takes forever to find, because it seems to work correctly half the time (when the comarison should be false).

A good habit to get into if you're going to do anything in C, C++ or other languages that aren't as strictly typed as JAVA, is to put all constants first:
Code:
if( 0 == asciiRange[i] )
that way in C/C++ if you left out one of the equal signs it would think your trying to assign to the constant 0.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top