Empty code block in a for loop
Demonstration of empty code block in a for loop for using the loop as a delay loop.
Learning Objectives
- Empty code block of a for loop.
- Delay using for loop.
Source Code
|
|
Run Output
Code Understanding
cout<<“Wait a few seconds!” <<“Some message will soon be displayed.”<<endl;
This message is displayed to user for asking him to wait for a message and not keep pressing other keys in a hurry.
for(int i=1;i<999999999;++i);
This is the for loop with large value of integer incrementation. The loop is followed by a semicolon (;) to indicate that there is not code inside the loop body. These kind of loops may work as a delay creating loops. However in modern days there are better functions available for delay functionality, but here we are just showing a demonstration. These delays will be system speed dependent.
cout<<“Delayed .. Hello!”<<endl;
This message will come after a delay. If your system is too fast this delay may not be visible. If it is too slow this may be quite high.
Notes
- One may have to adjust the data type declaration as per the system and compiler he is working on. int in old dos based machines or compilers may be just 2 bytes, so long declaration will be required there.
- For loop delays may be useful in some hobby projects which are hardware specific. In modern practical application one will need functions that can control the delay amount as per user wish. You can read about delay, sleep, usleep, sleep_for, sleep_until type of functions which are implementation and library availability dependent.
Common Errors
- Some programmers put ; even in the programs where for loop code block is available.
Suggested Filename(s): empty-for-code.cpp
Created: 1-Jan-2018 03:30 | Updated: 15-Sep-2018 12:33|
