Monday, 15 August 2011

c++ - While loop ends prematurely -



c++ - While loop ends prematurely -

i trying out "while" loop while reading c++ tutorial. surprisingly below loop exits on 2nd iteration despite gave negative integers.

while(int sz = get_size() && sz <= 0) ;

below get_size() used.

int get_size() { int = 0; cin >> a; homecoming a; }

your problem statement equivalent to

while(int sz = (get_size() && sz <= 0)) ;

which undefined behavior first iteration because sz uninitalized. solution moving declaration outside of loop.

int sz; while((sz = get_size()) && sz <= 0) ;

c++

No comments:

Post a Comment