Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
Hi, I have a function in a small project, This function contains a nested loop the outermost loop increments by 1 it satisfies the condition but it executes the loop body once. if i = 1 , j = 1 then x = 3 and y = 3 - I'm sure about these values using the debugger - but i becomes 2 then 3 without executing, it works only if I = 1.
C++
bool is_available_in_box(const short& num,const short& box_index)
{
    short place = get_location(box_index);
    short i = place / 10 , j = place % 10;
    short x = i + 2 , y = j + 2;
    for (i = i; i <= x; i++)
    {
        for (j = j; j <= y; j++)
        {
            if ( game[GAME_BOARD][i][j] == num )
            {
                return false;
            }
        }
    }
    return true;
}


Where is the problem ??

Thanks, Samuel.
Posted
Comments
PIEBALDconsult 1-Jul-15 14:40pm    
for (j = j ?


And probably better not to use for loops in that function anyway.
Sergey Alexandrovich Kryukov 1-Jul-15 16:31pm    
1) What do you want to achieve? 2) use the debugger.
—SA

1 solution

Self assignments (i=i; j=j;) as already noted by PIEBALDconsult, are useless.

In any case, your outer loop should be executed exactly three times, and for each of such iterations the inner loop should be executed exactly three times.
[update]
As PIEBALDconsult pointed out j=j is a mistake (I overlooked it): at first outer loop iteration it is useless but harmless. Since second outer iteration, however, j=j is equivalent to j=y+1, preventing inner loop execution.
[/update]
However, at any iteration, if the condition
C++
game[GAME_BOARD][i][j] == num
is true then the loops are immediately exited due to the
C++
return false;
statement.
 
Share this answer
 
v2
Comments
PIEBALDconsult 1-Jul-15 16:16pm    
Actually, the i=i is merely useless, whereas the j=j is even wronger than that.
Sergey Alexandrovich Kryukov 1-Jul-15 16:32pm    
"Wronger" is great concept. :-)
—SA
Richard Deeming 1-Jul-15 16:38pm    
That sounds like the answer to me! :)
CPallini 2-Jul-15 2:27am    
Yes, you are right, I overlooked that. Thanks.
Sergey Alexandrovich Kryukov 1-Jul-15 16:32pm    
5ed.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900