Yahoo Answers is shutting down on 4 May 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

C Programming For Loop question?

int foo(int x1, int x2) //sorry for the bad indenting, yahoo doesn't like it...

{ return x1 +x2;

}

int scum(int r)

{ for(i=0;i=2;i++)

foo(r+i, 5);

}

main()

{ scum(3);

}

// Does Foo ever execute? i=2 is an assignment statement where there should be an argument. since this is = and not ==, does it read it as a true statement? If this is true, wouldn't this be an infinite loop?

Update:

The problem is i=2, this is out of a book. I'm just trying to understand what exactly would happen

4 Answers

Relevance
  • 9 years ago
    Favourite answer

    It doesn't compile as is, since i isn't declared in scum (unless you havea a global variable i?

    But yes, it is an infinite loop.

    In C, x = y is an expression that does 2 things:

    It assigns the value y to x, of course.

    It evaluates to the the value y

    That is why you can do things like:

    a = b = c = 1;

    c = 1 sets c to 1, and evaluates to 1.

    So 1 is then assigned to b, and that evaluates to 1

    Which gets assigned to a.

    Same thing happens in your for loop. 2 gets assigned to i, and the expression is evaluated as 2

    In C, anything that isn't 0 is true. Values of 0 are false.

    So, in the condition for the for loop, you have an expression that evaluates to 2, which, since it isn't 0, is true.

    So the loop will never terminate.

    A good C compiler will generate a warning when you write code like that. It's a very common mistake in C. Even experienced programmers do it (not because they don't know better, it's just a typo. But you can waste a lot of time looking for it if the compiler doesn't even give you a hint.)

  • 9 years ago

    for(i=0;i=2;i++) is not right because i=2 should either be i!=2 which means does not equal 2 which would loop it until it was 2 or i==2 which would loop while it equaled 2,

  • 9 years ago

    inside the for loop the condition is i=2. That is, i value becomes 2 always. Thus, for loop condition becomes true always. Thus, loop becomes infinite loop.

  • 6 years ago

    confusing aspect. browse using google or bing. it could actually help!

Still have questions? Get answers by asking now.