If, For, While, Loops--What's the difference?

Hi, I am wondering what the difference between if, for, and while loops is. I tried interchanging them in any code and the results are the same. For example, if I have an LED turn on if I press a button, it will still turn on when I have it turn on, for and while I press a button.

Thanks.

Have you read about them in the reference section? They do a pretty good job of explaining them there. There are also hundreds if not thousands of C++ tutorials on the web you could go through that would explain it. Google is great at finding them.

Yes, I looked at them and while I sort of understand their definitions them I don't understand why all three commands will work to light an led. Also, is one of them better than another?

Since not all those are loops, it is hard to see what you did.

The usage pretty much follows the English meaning.

if is for comparison. if a condition is true, execute a statement or a compound statement in braces.

for () executes a set of statements a certain number of times.

while() executes a set of statements while a condition is true.

Hie thee to K&R!

Vulcan666: Yes, I looked at them and while I sort of understand their definitions them I don't understand why all three commands will work to light an led. Also, is one of them better than another?

Show the code you used.

There are many ways to accomplish the same thing is almost all programming languages.

They might all seem to work the same because you have the loop function repeating.

Do you not understand that a for loop runs so many times, a while loop runs until a condition is met and an if statement is evaluated only once?

Do your coding in setup instead of loop and I think you'll see the difference.

I see about the difference you made and that makes sense. Okay, so I ran some different code so that the condition for the while loop was met it wouldn't go anymore. I tried what you said Delta G and got different results. Now it all makes sense.

Thanks for all your help!

Delta_G: Do you not understand that a for loop runs so many times, a while loop runs until a condition is met and an if statement is evaluated only once?

I ran across this post while trying to teach myself Arduino and I just wanted to say thanks for this concise comparison of these three functions! I have been reading a lot of forum posts and tutorials but hadn't seen these cases so clearly laid out like this. THIS makes the connection for me. :)

'if' is not a loop. It is a statement. You'll only confuse yourself if you think of it as a loop.

Pete

el_supremo:
‘if’ is not a loop. It is a statement. You’ll only confuse yourself if you think of it as a loop.

Pete

You are correct, I am now confused. :confused:
I just used the following lines of code to successfully perform a counted loop -

void loop()
{
for (int x = 0; x = ++x;)
if (x <= 5)
{//turn an LED on and then off}

else {//turn a different LED on}
}

That block will loop the “turn LED on and off” lines of code for as many times as I enter in the “if” condition.
Not being confrontational here, I’m just trying to understand why that isn’t considered a “loop”.

Thanks

Gary_Arduino: You are correct, I am now confused. :confused: I just used the following lines of code to successfully perform a counted loop -

That block will loop the "turn LED on and off" lines of code for as many times as I enter in the "if" condition. Not being confrontational here, I'm just trying to understand why that isn't considered a "loop".

Thanks

That's like asking why a cow isn't a barn, because it's inside a barn.

Gary_Arduino:
You are correct, I am now confused. :confused:
I just used the following lines of code to successfully perform a counted loop -

That block will loop the “turn LED on and off” lines of code for as many times as I enter in the “if” condition.
Not being confrontational here, I’m just trying to understand why that isn’t considered a “loop”.

Thanks

The for statement is the loop. It is doing the looping. Within each iteration of that looping, the if statement only executes once. So the if is not a loop. The if is IN a loop.

That’s not how something like that would normally work. Normally you put the test in the for loop.

for (int i = 0; i <=5; i++){

and you wouldn’t have an if statement in there to test for i. The way you have it written once it stops flashing the LED that for loop of your continues to run doing nothing until it wraps around to 0. That’s pretty much a waste.

void loop()
{
    for (int x = 0; x = ++x;)
        if (x <= 5)
    {
        //turn an LED on and then off}
    else 
    {
        //turn a different LED on}
    }
}

Beware - that short piece of code has several errors:
First, the behavior of “x=++xx” in indeterminate. Per c/c++ specifications, the outcome of that instruction is undefined. If you want to know why, Google “c++ sequence points”. In any case, if your intent is to increment x after each iteration of the loop, simply using either “++x” or “x++” is the correct thing to do.
Second, a for statement has three parts: initializer, test, increment. The initializer (x=0 in this case) is executed. Then the test (x=++x, in this case) is evaluated, and, if the result is false/0, the loop is terminated. Finally, AFTER each iteration of the loop, the increment expression (which you did not provide) is evaluated. So, what is the above code doing?

  1. First it sets x=0
  2. Immediately updates x based on “x=++x”, which does… Who knows what? The result can/will be different when compiled for different compilers, or on different systems. So, you have no guarantee WHAT that expression will evaluate to. On some systems, it may well evaluate to 0, which means the loop runs forever, and x is always 0 for all iterations of the loop. Probably not what you want. On another system, it may always evaluate to true/1, which means the loop never runs even once. Probably also not what you want. On some systems, the result may be random. Almost certainly not what you want. Even if the code does what you want (increment x), the first iteration of the loop may execute with x=1 instead of x=0. So, if you think the code worked, it did so as much by dumb luck as anything else.
    The correct way to write that code would be:
void loop()
{
    for (int x = 0; x < 10; x++)
    {
        if (x < 5)
        {
            //turn an LED on and then off}
        else
        {
            //turn a different LED on}
        }
    }
}

Regards,
Ray L.

Thanks Ray!
There is a wealth of info in your post. I have been getting info from lots of google searches and forum posts and now start to fear that I may be mistaking similar but different expressions that people have used in their examples as interchangeable. For instance x++/++X/x = +xx … all of which I have seen as ways to increment a variable. I mistook them as being interchangeable and I seem to have made that mistake with other code.
Just need to keep working at it.

Ray i couldnt get the part for(x=0;x=++x) Doesnt for loop require 3 conditions ? And when omitting one of them there must be empty “;”? Second part in for is test part where it must be tested against something x=++x is test or assignment? ++ has higher precedence then = so its assigning end result of x to x.

And one question about for loops. Suppose there is function with for loop inside and there is variable declaration in initializer section as We cant access variable of that for loop outside of for Are we freeing up memory when for loops terminates?

surepic: Ray i couldnt get the part for(x=0;x=++x) Doesnt for loop require 3 conditions ? And when omitting one of them there must be empty “;”? Second part in for is test part where it must be tested against something x=++x is test or assignment? ++ has higher precedence then = so its assigning end result of x to x.

And one question about for loops. Suppose there is function with for loop inside and there is variable declaration in initializer section as We cant access variable of that for loop outside of for Are we freeing up memory when for loops terminates?

Yes, there should be three expressions, as I explained. He DID have a trailing ; making the third expression a null statement. Using an assignment as the second expression is perfectly legal, and the target of the assignment will be evaluated to determine whether or not to loop. x=++x and x=x++ will both produce can produce different results on different compilers and different processors. This is just a fact of life with c and c++, and has been since c was first created in the '70s. There is NO guarantee the final value of x will be the initial value of x incremented by 1. Operator precedence is not the issue, and explaining WHY this is so would be WAY too much work. Google "c++ sequence points" if you want to learn more. x=x+1, y=++x or y=x++ will ALWAYS produce the expected result, but NOT x=++x or x=x++. Any memory allocated to non-static local variables in ANY scope are released when that scope is exited. Not just within loops, but within ANY scope:

void loop(){
int w = 1;
  Serial.print(w);
  {
    int x = 2;
    Serial.print(x);
    {
      int y = 3;
      Serial.print(y);
      {
        int z=4;
        Serial.print(z);
      } // z memory is released
    } // y memory is released
  } // x memory is released
} // w memory is released

Regards, Ray L.

Vulcan666: Hi, I am wondering what the difference between if, for, and while loops is.

Google "C++ tutorial", and do a C++ tutorial. Taking a couple hours to do that will work much better for you than asking bitsy questions and getting bitsy answers.