I got stuck while playing with while loop. Can you help me?

Continuing the discussion from What's wrong with this code?:

I’ve a doubt, why writing " k+= b; " on different line gives different answer? How is this possible??

while (k+b <= n && t[k+b] <= x)
k += b;

while (k+b <= n && t[k+b] <= x) k += b;

In this case, it doesn’t. Why do you think it does?

I run both the codes with writing k+=b; on two different lines and it gave me different answers. ( on codechef compiler)

The code here:

gives an out-of-bounds access irrespective of whether k += b; is on the same line as the while or not. Out-of-bounds accesses are Undefined Behaviour, so you might not get the same result each time.

1 Like