Reputation:
I have the following code snippet where 'b' is an integer array, MAX is an integer and an integer 'ans' stores the result. I'm debugging some code and am not very familiar with C++ as I use Java. The C++ code is:
for(i=0; i<MAX; i++)
ans+=(b[i]!=-1);
The way I have understood it is as:
for(int i=0;i<MAX;i++)
if(b[i]!=-1)
ans+=b[i];
However, I get an absurd answer with the logic above. What does the statement really mean?
Upvotes: 3
Views: 139
Reputation: 262
Parenthesis around something means that it will return a boolean: true or false. However, Java stores these in boolean values. C++ stores them as 0 or 1 values For example, (1=1) or (character.x <= object.y). Therefore, as long as the statement returns true, or the value of B index i will not be -1, then it will proceed to add 1, or true. If it is false, it will add 0, or false. To do this in java, just add a conditional statement, checking if b index i is not equal to -1:
for()... if (b[i] != -1)... answer = answer + 1, or answer += 1, or answer++;
Upvotes: 0
Reputation: 12883
for(i=0; i<MAX; i++)
ans+=(b[i]!=-1);
C/C++ evaluates this (b[i]!=-1)
to either 0 or 1. In java, that evaluates to a boolean value (true or false), and Java does not convert booleans to integers automatically. However would is very easy to do on your own.
e.g.
for(i=0; i<MAX; i++)
ans+=(b[i]!=-1) ? 1 : 0;
ought to work just fine.
Upvotes: 1
Reputation: 1074
Your code block is very strange in C++. I think the clearest way to answer your questions is to tell you exactly what it actually says.
for(i=0; i<MAX; i++) // Normal loop. Nothing strange here
ans+=(b[i]!=-1); // Let's look at this more closely
The inner statement is saying ans += VALUE_OF_AN_EXPRESSION
. What expression's value are you adding to ans? This expression: b[i]!=-1
. What's the operator there? Its !=
which is a boolean operator, so it returns true/false. In C++ true is treated as 1 and false as 0, but this is really not relevant because even in Java it doesn't make sense to add a boolean to an integer.
Hopefully this is more clear.
Upvotes: 0
Reputation: 37655
I think the Java equivalent is
for(int i=0;i<MAX;i++)
if(b[i]!=-1)
ans++;
In C++, a true statement evaluates to 1
. Java does not do that so you have to explicitly increment ans
.
Also, note that if MAX
is the length of the array (I don't know if it is or not) you can use a for each loop.
for (int a : b)
if (a != -1)
ans++;
Upvotes: 8