# Thread: Less than or equal - precedence in for loops

1. ## Less than or equal - precedence in for loops

Some thing that I've been wondering about for a while, is the precedence of < (less than) and <= (less than or equal). As far as I know, these operators have the same precedence.

Now, take this for an example:
Code:
```	int	i;

for (i = 0; i < 4; i++)
{
printf ("%d\n", i);
}```
Would print 0, 1, 2, 3. However, if I change it so:
Code:
```	int	i;

for (i = 0; i <= 4; i++)
{
printf ("%d\n", i);
}```
It prints 0, 1, 2, 3, 4. So what's the deal? In the second code snippet, it loops while i is less than or equal to four. In the first example, it loops while is less than four. Can someone explain to me why this behaviour - i.e. the second example should (in theory) yield the same results as the first example, right?

2. No.

Precedence is the same -- precedence only means the order of operations. In arithmetic, + and - have the same precedence, but they aren't the same operation at all.

As you say, the 2nd code loops while i is less than or equal to 4. That's the condition in the loop -- whenever the middle part is true, the loop executes again.

So if the condition is i < 4, then it will execute as long as i is less than 4. When the condition is i <= 4, it loops as long as i is less than or equal to 4.

Precendence has absolutely nothing to do with this; precedence only affects expressions with many parts. E.g.

i = 1 + 2*3;

is guaranteed to yield 7, not 9, because the "*" operator is higher precedence than "+", so the multiplication, being higher precedence, happens first. The assignment operator, "=", is very low precedence and happens last. The above assignment evaluates just like:

(i = (1 + (2 * 3)));

and NOT like:

(i = ((1 + 2) * 3));
or
(((i = 1) + 2) *3);
or anything else.

Precedence only impacts the order of operations in a single expression. It doesn't mean that < and <= give the same answer (and intuitively, they should NOT. 4 < 4 is false, 4 <= 4 is true).

3. "Now that I come to think of it..." - Thanks, that answered my question!

Edit: Oops!

4. for (i = 0; i <= 4; i++)

For i is equal to zero, and is less then or equal to 4, something is done, at the end one is added to i.

If you put
for (i = 0; i == 4; i++)

i must = 0, and 4 at the sametime to do anything. Which is impossible. Thats why nothing is printed.

I'm still learning C, so I may be wrong. So don't quote me.

5. Originally posted by twigg
If you put
for (i = 0; i == 4; i++)

i must = 0, and 4 at the sametime to do anything. Which is impossible. Thats why nothing is printed.

I'm still learning C, so I may be wrong. So don't quote me.
Yes and no. Yes you're right, but no, it's not worded very well.

First you give "i" the value of zero.
Next, you say if this test is true, do whatever is in the loop. The test being "i == 4" fails because you have set it to 0.
The loop ends, and "i" is never incremented. The body of the loop is never executed.

Quzah.