I’m having a problem and can’t seem to find the solution..
int linearSearch(nodeptr list,char search){
int pos =0;
if(list==NULL)
return -1;
while(list->info!=search && list!=NULL){
pos++;
list=list->next;
}
if(list==NULL)
return -1;
else
return pos;
}
I always get a runtime error.. 🙁
should be:
This is called as Short-circuit evaluation.
When you use
&&the first expression is guaranteed to be executed before the second for inbuilt primitive types[#1].In your case the dereferencing happens before the
NULLcheck, So whenlist == NULL, You will end up derefrencing theNULLand causing an Undefined Behavior and a crash.In the sugeested solution:
if
list == NULLthen the second condition will not be evaluated.Reference:
[#1]C++03 Standard 1.9.18: