'do...while' vs. 'while' 'do...while' vs. 'while' c c

'do...while' vs. 'while'


If you always want the loop to execute at least once. It's not common, but I do use it from time to time. One case where you might want to use it is trying to access a resource that could require a retry, e.g.

do{   try to access resource...   put up message box with retry option} while (user says retry);


do-while is better if the compiler isn't competent at optimization. do-while has only a single conditional jump, as opposed to for and while which have a conditional jump and an unconditional jump. For CPUs which are pipelined and don't do branch prediction, this can make a big difference in the performance of a tight loop.

Also, since most compilers are smart enough to perform this optimization, all loops found in decompiled code will usually be do-while (if the decompiler even bothers to reconstruct loops from backward local gotos at all).


I have used this in a TryDeleteDirectory function. It was something like this

do{    try    {        DisableReadOnly(directory);        directory.Delete(true);    }    catch (Exception)    {        retryDeleteDirectoryCount++;    }} while (Directory.Exists(fullPath) && retryDeleteDirectoryCount < 4);