Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.c++ > #11024
| From | Markus Wichmann <nullplan@gmx.net> |
|---|---|
| Newsgroups | comp.lang.c++ |
| Subject | Re: loop problem |
| Date | 2011-10-20 18:20 +0200 |
| Organization | Aioe.org NNTP Server |
| Message-ID | <qbu5n8-e32.ln1@voyager.wichi.de.vu> (permalink) |
| References | <24519ed1-c869-41ee-931a-3896cca4db97@gk10g2000vbb.googlegroups.com> |
On 20.10.2011 17:18, fattaneh wrote:
> hi all ,
> i have written this code , and it should be in while if num is not
> zero
> so it shouldn't print error , but num becomes zero and it wont come
> out of while
> i have written this code in visual studio c++
>
> #include "stdafx.h"
Doesn't look much like standard...
> #include <stdio.h>
> using namespace System;
>
> int main(array<System::String ^> ^args)
^^^^^^^^^^^^^^^^^^^^^^^^^
Definitely _not_ standard. The standard is one of:
int main()
int main(int argc, char* argv[])
or equivalent. (There are two other forms for argv that mean exactly the
same.)
> {
> int num =5 ;
> while (num !=0)
> {
> num-- ;
> if(num ==0)
> {
> printf("error") ; // it should never write this but it
> will write .
> }
> }
> return 0;
> }
>
>
> could you help me to filnd out what the problem is ?
>
> thanks of all . . .
Short: Move the decrement instruction to the other side of the loop!
Long: The condition of a while-loop is checked only on entry and on
repeat, not after every instruction inside the loop. Thus, if num is 1
at the beginning of the loop, it is decremented to 0, then the if fires.
HTH,
Markus
Back to comp.lang.c++ | Previous | Next — Previous in thread | Find similar | Unroll thread
loop problem fattaneh <fattaneh.69@gmail.com> - 2011-10-20 08:18 -0700
Re: loop problem Leigh Johnston <leigh@i42.co.uk> - 2011-10-20 16:34 +0100
Re: loop problem fattaneh <fattaneh.69@gmail.com> - 2011-10-20 08:39 -0700
Re: loop problem Markus Wichmann <nullplan@gmx.net> - 2011-10-20 18:20 +0200
csiph-web