When is a do-while appropriate?

后端 未结 13 1767
Happy的楠姐
Happy的楠姐 2020-11-30 09:15

When is a do-while the better choice over other types of loops? What are some common scenarios where its better than others?

I understand the function of a do-while,

相关标签:
13条回答
  • 2020-11-30 09:38

    Another exception when you are doing something recursive, like the following with reading inner exceptions:

    catch(Exception exc)
    {
        Exception currentException = exc;
        do
        {
            Console.WriteLine(string.Format("{0}: {1}", currentException.GetType().Name, currentException.Message));
        } while((currentException = currentException.InnerException) != null);
    }
    
    0 讨论(0)
  • 2020-11-30 09:45

    No-one's yet mentioned its use in C macros...

    #define do_all(x) do{ foo(x); bar(x); baz(x); } while(0)
    

    then in the code you can have

    do_all(a);
    
    • the point being that it gets executed exactly once and the semi-colon on the end of the macro call completes the while(0); statement.
    0 讨论(0)
  • 2020-11-30 09:47

    do while() loops while a condition is true, but on the other hand, Pascal's repeat until loops while a condition is false (both will run at least once).

    When I program in Pascal I almost always use repeat until.
    When I program in C++ I almost always use while() {}.

    I can't explain why, but I feel it's normal. Weird?

    0 讨论(0)
  • 2020-11-30 09:49

    when reading from a file or waiting for a connection to be established (other human interaction as well), anything for what the number of iterations is not known a priori (e.g. number of records returned by an sql query), or when you do steps of different size (e.g. read 1 or 5 lines from the file depending on the last one read), when going over all combinations/permutations of objects, whenever 'for' loop conditions become cumbersome

    0 讨论(0)
  • 2020-11-30 09:50

    Normally when you need the user to input some value, the counter variable is based on the input value, you use do-while. //The following code is in C++. It requires the user to input a number and repeats until users input number larger than 0.

    do{
        cout << "Enter a Positive integer: ";
        cin >> num;
    }while( num < 0 );
    
    0 讨论(0)
  • 2020-11-30 09:51

    I usually use a do-while when something needs to happen, but it won't necessarily happen "correctly" on the first time. For instance:

    int x;
    do
    {
        x = random.next(100);
        cout << x << endl;
    } while (x != 13);
    

    In this case, the x you start with doesn't matter at all, because it's overwritten.

    0 讨论(0)
提交回复
热议问题