Reputation: 23
I'm quite new to C++ and I have some kind of problem. I would like to ask if someone could explain to me why the evaluation within the for condition does not work.
This is a part of a program I've written, there is a rpm value which is given by the user and gets assorted to a rpm_case to do some calculations later.
What it SHOULD do:
========================================================================
in the first place I had some 30-line long if-construction for that but I discarded that already and replaced it with the following much shorted and nicer way to write it (this works as expected):
const float rpm_bases[known_rpm_bases] = {800, 1200, 1800, 2500, 3500};
short rpm_case;
for (rpm_case=0;; rpm_case++) {
if (!(rpm > rpm_bases[rpm_case+1])) {break;}
}
but I'm still not happy because I was really trying to get rid of the if with the for loop. But the for- loop instead always loops over the entire size of the array instead breaking at the considered point.
const float rpm_bases[known_rpm_bases] = {800, 1200, 1800, 2500, 3500};
short rpm_case;
for (rpm_case=0; (!(rpm > rpm_bases[rpm_case+1])); rpm_case++) {}
?? It somehow seems as it is not possible to evaluate a array with the counter-variable within the conditional part of an for-loop??? Or am I just doing something totally wrong I don't want to exclude that option either.
Big Thanks to everyone in advance.
Upvotes: 2
Views: 233
Reputation: 25385
The middle expression of a for
statement is the condition that must be true for the loop to repeat. Therefore, it must be the opposite of the condition that must be true for the loop to break.
For this reason, you must negate the expression by removing the !
(NOT) operator, like this:
for (rpm_case=0; rpm > rpm_bases[rpm_case+1]; rpm_case++);
This expression will work for the cases stated in your question. However, if rpm
is higher than 3500, it will cause the array rpm_bases
to be accessed out of bounds, causing undefined behavior. Therefore, it would be safer to write the loop in the following way:
for ( rpm_case=0; rpm_case < known_rpm_bases; rpm_case++ )
{
if ( rpm <= rpm_bases[rpm_case] ) break;
}
That way, your program will just give you an additional increment of rpm_case
if rpm
is higher than the highest value, instead of accessing the array out of bounds causing undefinied behavior.
Upvotes: 2
Reputation: 17464
This is effectively just a typo.
The loop condition is for how long the loop does keep running, not to describe when it ends.
Invert it.
Upvotes: 2