mike - 1 year ago 190
C++ Question

# Break if statement c++ error

I'm writing linear and quadratic probing hash table program.

This is a for-loop I used for linear probing function and it works perfectly fine.

``````//when there's a collision increase i by 1 until finding empty slot
for(i = (hashVal % tableSize+1) % tableSize; i <tableSize; i++)
if(a[i] == -1){
a[i] = hashVal;
break;
}
``````

so I wrote a for loop again in quadratic probing function to deal with collision

``````//when there's a collision increase i by i^2
j = 0;

for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
j = i^2;
if(a[j] == -1){
a[j] = hashVal;
break;
}
``````

But when I compile quadratic probing, I'm getting this error

``````error: 'break' statement not in loop or switch statement
``````

I am really confused why it causes error in the second one while it is fine in linear probing. Could anyone explain why?

``````for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
j = i^2;
``````

this is your cycle, since you didn't put curly braces around it.

fix is simple, put those braces:

``````for(i=((hashVal % tableSize+1) % tableSize); i < tableSize; i++)
{
j = i^2;
if(a[j] == -1){
a[j] = hashVal;
break;
}
}
``````

Rule of thumb - always put curly braces when you use cycle or if-statement, because it helps you to not make such errors as this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download