Could someone please explain these for loops to me?

+1 Toyen . · November 19, 2015
Hello everyone,

I have some for loops here which I am not really sure why they should be working the way they are described and I' d be much obliged, if anybody could clear this up for me.

First one:

int x;

for( x = -3; ++x; x++)
puts("something");

The question is, how many times this loop will run and what will be the value of x when it finishes. The correct answers should be that it will run just once, and the value of x will be 0.

I think I understand why it will only run once (because the condition is to keep running until we increment x and this is exactly what we are doing from the beginning?) but how the hell can x = 0?

Second one:

int x;

for( x = -5; x--; x = x&1)
puts("something");

The same question, how many times this will run and what is the final value of x when it stops. The correct answers should be that it will run just once and the final value of x is -1.

I think I am a bit puzzled here.

The condition here is that it will run until x becomes negative, right?

So the result of the binary operation -5%1 which in binary with 5 positive would be 0101&0001 = 0001 which is 1 but we have a negative 5 so it will be -1?

Is that right?




Post a Reply

Replies

Oldest  Newest  Rating
+1 Dan P · November 20, 2015
Hi Toyen,

For your first example what happens is,

1. x is set to -3.
2. The increment operator is a pre-increment operator on the condition in the for loop, 
therefore ++x = -2.
3. We call the puts() function
4. We run the update expression x++, therefore x = -1.
5. Now we check the condition again, if the condition is false or 0, we exit the loop. As we increment the x var before we test
x is now 0, therefore the loop will exit.

With the second example:

1. x is set to -5.
2. The condition is -5, therefore run the loop.
3. x is decremented to be -6.
4. Call the puts function.
3. You do a bitwise logical operation which means 6 & 1 = 0. Therefore x = 0.
4. Check the condition again, x = 0, decrement 1 and exit the loop.
5. x = -1.

Hope this helps. :)
  • 1

C

107,105 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator