InterviewSolution
| 1. |
What is the output of the following code: |
|
Answer» INT main() { for(;;) std::cout<<"hello\n";} Let us see what for does. for loop does 3 things, initialization, condition check and expression to evaluate before running the next iteration. These 3 things are separated by a semicolon (;). Whatever logic is needed inside for loop is placed inside { } parenthesis. If we have a SINGLE line body then this single line can follow for loop without having the { } parenthesis. One more thing to note is that when the condition check is empty, it is replaced by a non-zero constant by the compiler. for(;;) // This is fine because condition is replaced by nonzero-constant by compiler as per the specification of C++ languagewhile() // This gives an error as it doesn't have condition expressionif() // This also gives an error as it doesn't have condition expressionHere, in this case, the initialization is empty, condition check is empty and the expression to evaluate before running the next iteration is also empty and has a single line body of the print statement. As the condition is replaced by a non-zero constant by the compiler, it is always evaluated to true and hence the loop runs on forever. So an INFINITE loop printing Hello on the SCREEN. |
|