CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: loop question

  1. #1
    Join Date
    Mar 2011
    Posts
    52

    loop question

    can someone explain why this loop calls the function in it?
    when i called the function in the loop it called it twice.
    i had the understanding that a loop laid out like != would just check a condition.
    here is the code

    Code:
    do{menu();}
         while(selection(files) != true);
    selection is declared bool.
    tried to find a good explanation but couldn't.could someone go into detail about this?

  2. #2
    Join Date
    Aug 2009
    Location
    Romania->Felnac
    Posts
    48

    Re: loop question

    You need to debug the code and see what selection(files) returns.

    And the difference between the do...while and while is in principle that do..while always executes the do code block at least once (even if the condition is false from the beginning)

    So this code will print Foo once:
    Code:
    do {
    std::cout << "Foo\n";
    }
    while(false);
    And this code doesn't print Foo:
    Code:
    while(false) {
    std::cout << "Foo\n";
    }

  3. #3
    Join Date
    Mar 2011
    Posts
    52

    Re: loop question

    thank you
    but i understand the dif. between do while and while
    i think i understand what is going on.
    if you call a function to check a condition it will actually call the entire function not just read the end result as i had assumed.
    the entire function will run in order for the condition to be checked.
    i thought it would check the last returned true or false and i was wrong.

  4. #4
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: loop question

    Yeah, if you stop to think about it for a moment, it will become clear why that would be much less intuitive from a programmer's perspective. Far simpler to just remember the rule----if you want to keep the last value returned by a function around somewhere, store it in a variable.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured