[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: gcc: A while Loop Always Skips its first Statement.



Martin McCormick wrote:
I have written some C code that appeared to be good until I put
a while statement in to one of the modules and then all went to
at least Purgatory. It all compiles beautifully but I was
alerted to something terribly wrong when the program began
misbehaving. I can't even say that it is flaky because it does
exactly the same wrong things every time without fail.

	There is a variable I call NEXTSYS which is boolean and
my while statement now looks like:

while (NEXTSYS) { /*code to execute if NEXTSYS does not = 0*/
C statements (It doesn't seem to matter what statements);
} /*code to execute if NEXTSYS does not = 0*/

	What happens every time is that gdb traces perfectly up
to the while statement, skips it, and executes the statements
inside the braces. After that, it is in the while loop and
execution looks normal but the damage is already done. I have
also seen it trace the wile statement and then skip the next
executable statement in the loop no matter what it is.

	Reading about the while loop tells me that the statement
after while must be true to execute. If I put a boolean variable
inside the statement as in (NEXTSYS) does that make a true
statement if it is not 0 and false if it is?

Thanks for any constructive answers.

I'd rather do it in code and use caps for compiler defines and lower case for program variables. Also I prefer to use C++ because it debugs better and I don't use gdb because it is too fine grained but rather use printf statements, like this:

#define NEXTSYS 1
#include <stdio.h>


int main( int argc, char **argv, char **envp )
{
    int count = 0;
    while ( NEXTSYS ) {
	printf("Inside the while loop, count = %d (%d)\n",count,__LINE__);
	count++;
	if ( count > 10 )
	    break;
    }
    printf("Outside of the while loop, count = %d (%d)\n",count,__LINE__);
    return 0;
}


and running it:


hugo@debian:/sda7/hda10/backup.files/fromhd/home/hugo/gpc-qt4-002$ ./do_martin
Inside the while loop, count = 0 (9)
Inside the while loop, count = 1 (9)
Inside the while loop, count = 2 (9)
Inside the while loop, count = 3 (9)
Inside the while loop, count = 4 (9)
Inside the while loop, count = 5 (9)
Inside the while loop, count = 6 (9)
Inside the while loop, count = 7 (9)
Inside the while loop, count = 8 (9)
Inside the while loop, count = 9 (9)
Inside the while loop, count = 10 (9)
Outside of the while loop, count = 11 (14)




Hugo








Reply to: