-
infinite loop error
why am i getting an infinite loop in this piece of code:
Code:
while((( *(str+index)) != '(') || ((*(str+index)) ! = '\0'))//while char is not '(' and not end of string, increase index
{
index++;
}
Is it because i should have flushed something and i didn't??
If that's the case how do i do that??
coz i've been trying delete [] str;
and this doesn't work
-
It can't be both '(' and '\0' at the same time. Thus, it should be "while it isn't this AND it isn't that".
Also, delete is a C++ keyword.
Quzah.
-
try
Code:
if( index < strlen(str) && index >= 0) /*be sure...*/
while( str[index] != '\0' && str[index++] != '(' );
-
> while( str[index] != '\0' && str[index++] != '(' );
Would be better written as
while( str[index] != '\0' && str[index] != '(' ) index++;
Remember, && and || are short-circuited, so if the right hand side is skipped, then the side effect of the ++ DOES NOT HAPPEN!
Needless to say, this is a bizarre bug to find.
-
you even put in your comment
//while char is not '(' and not end of string, increase index
make it && and it should work.
Also with this line:
while( str[index] != '\0' && str[index++] != '(' );
remember that i++ is postfix and depending on the order that you want things to happen and if you want index to increase, that statement is undefined.
It is undefined because the while could evaluate from the right, then index would be increased for str[index] but not for str[index++]. But since it is postfix, if you want it to increase and it evaluates from the left it won't be increased for the evaluation. Then also what the guy before said, if the left hand side is false the right hand side won't even be evaluated (that is of course if it evaluates from left to right). So I wouldn't be doing that since you don't know what order things are all going to occur in.
-
> It is undefined because the while could evaluate from the right,
No - the order in which && and || are evaluated is very specifically defined.
-
This while loop, while it works, seems overly complex & is causing headaches. Why not just search for a '(' using strchr() ? For example, any reason why this wouldn't work:
Code:
#include <stdio.h>
int main()
{
char *test = "Test! =) Good day.";
int index = 0;
char *cfind;
cfind = strchr(test, ')');
if(cfind) index = cfind - test;
else index = strlen(test);
printf("Index is: %d\n", index);
return 0;
}
-
Well it's beacause i'm converting my program from C++ to C and i didn't use any available method to find a character. Thanks to you all, i've found my mistake.
A really silly mistake i can say. :P
Sorry for all this trouble.