First code
#include<stdio.h>
int main()
{
while(printf("Hello"))
return 0;
}
Produces only Hello as a output
Second code
#include<stdio.h>
int main()
{
while(printf("Hello"));
return 0;
}
Second code prints Hello for infinite times.
Third code
#include<stdio.h>
int main()
{
while(printf("Hello"))
{}
return 0;
}
Third code also prints Hello for infinite times.
Compiler used - GCC 9.0.1
why this is happening?
while takes a statement after the closing ).
6.8.6 Iteration statements
iteration-statement:
while ( expression ) statement
....
In
while(printf("Hello"))
return 0;
that statement (which is basically while's argument) is return 0; (6.8.6)
In
while(printf("Hello"));
the statement is ; (an empty (null)/expression statement (6.8.3)).
In
while(printf("Hello")){}
it's an empty compound statement ({}, 6.8.2), which is semantically equivalent to ;.
Your code snippets are examples of misleading whitespace—where the whitespace makes humans understand things differently from a compiler.
Less misleading renderings would be:
while(printf("Hello"))
return 0;
,
while(printf("Hello"))
; //or perhaps a {} instead of the null statement
and
while(printf("Hello"))
{}
printf returns number of characters printed (which is 5). Any non zero number evaluates to true. So the loop is an infinite loop.
The rest depends on what happens withing the loop. In the second and third cases, the loops are empty (contain no statements) so they keep executing
In the first case, return 0 is executed within the loop. Return breaks the control flow out of the loop causing the loop (and in this case the program) to stop executing
In your first code snippet, the return 0; statement is part of the while loop's 'body'; in fact, it is the entirety of that body! So, on the first run through that loop, the program exits (because that what return 0; does when executed in main) and the loop is, thus, abruptly terminated.
In the second and third snippets, you have an empty body for the loop, but that does not prevent it from running, as the printf("Hello") function call will return the number of characters that were output - which will be non-zero, and thus interpreted as "true".
In the first one the body of the while is the return 0 so it will return after the first iteration. Meanwhile with the other two version is the same, having an empty body so they infinitely going on doing nothing but the condition is keep evaluating which will print "hello".
while(printf("Hello"))
return 0;
is same as
while(printf("Hello"))
{
return 0;
}
First Code:
printf("Hello") returns the number of characters.
When printf("Hello") is used inside while loop it will print Hello and return 5.
Since it is greater than 0 while loop consider this as true and execute the statement below the while, which is return 0.
The return 0 makes the main function to return 0 and stop the exeution.
The code
while(printf("Hello"))
return 0;
is same as
while(printf("Hello"))
{
return 0;
}
Second Code:
Since you used ; after while() ,it will not execute the statement after ;.
So the statement return 0 is not executed and while checks the condition infinite times printing infinite Hello.
Third code:
While will execute the statements only within the { }.
Since its empty every time after searching for statement it will go back and check the condition.
Since the condition is always true it will not reach the return 0 and it will print Hello infinite times.
Related
Could anyone explain to me why it prints 32 and the overall concept of how this works?
#include <stdio.h>
int main()
{
int a=1;
for (printf ("3"); printf ("2"); printf ("1"))
return 0;
}
Proper indentation would make it clearer:
#include <stdio.h>
int main()
{
int a=1;
for (printf ("3"); printf ("2"); printf ("1"))
return 0;
}
So the following happens:
a is initialized to 1. I don't know why this variable exists, since it's never used.
for executes its initialization statement, printf("3");. This prints 3.
for evaluates its repetition condition, printf("2"). This prints 2 and returns the number of characters that were printed, which is 1.
Since the condition is truthy, it goes into the body of the loop.
The body executes return 0;. This returns from main(), thus ending the loop.
Since the loop ends, we never evaluates the update expression, printf("1"), so it never prints 1. And we get no repetition of anything.
You know, a program begins to run from the left ‘{’ of function main(), end in the right '}' of function main(), if there is no endless loop.
As your code shows, Your difficulty is to understand the flowchart of the for loop in C language.
As you can see, The syntax of the for loop is:
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of loop
for loop body;
}
How for loop works?
1.The initialization statement is executed only once.
2.Then, the test expression is evaluated. If the test expression is evaluated to false, the for loop is terminated.
3.However, if the test expression is evaluated to true, statements inside the body of the for loop are executed, and the update expression is updated.
4.Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is false, the loop terminates.
So, for loop Flowchart
Firstly, Take your code as an example:
#include <stdio.h>
int main(){
for (printf ("3"); printf("2"); printf("1")) break;
return 0;
}
Output
32
1.initialization is "printf ("3")", then, print:
3
2.The test expression "printf("2")", that always true, so print:
2
3.for body loop "break", that means ending the execution of the for loop,
do not execute the updated expression "printf("1")"
also, the program jump out of the for loop, and jump to "return 0;",
then, end the the execution of this program.
So, the output is
32
Secondly, Take your changed code as an example:
#include <stdio.h>
int main(){
for (printf ("3"); printf("2"); printf("1")) ;
return 0;
}
Output
321212121212121212...121212...1212...
Similarly,
1.initialization is "printf ("3")", then, print:
3
2.The test expression "printf("2")", that always true, so print:
2
3.for body loop "``", empty, then do nothing. goto the updated expression
"printf("1")"
4.the updated expression "printf("1")", then, print
1
5.then, goto the test expression "printf("2")", that is "2.The test
expression "printf("2")", that always true, so print".Because the
the body of loop is "``",empty, then always goto from the updated
expression "printf("1")" to the test expression "printf("2")",
that's why after printing "32" that function prints infinite loop
"12".And, that function never end stop printing "12" unless you
stop that function.
So, So, So the output is
32121212...121212...121212...
Thirdly, Take your recently changed code as an example:
#include <stdio.h>
int main()
{
int a=1;
for (printf ("3"); printf ("2"); printf ("1"))
return 0;
}
Output
32
1.the program begins to run from the left ‘{’ of function main(),
that's the initialization statement of Temporary variable
"int a=1;".
That statement defines an "int" typed temporary variable "a", and
sets its value to "1", But that print nothing!
2.then, the program goto the for loop.
3.the initialization statement is "printf ("3")", then, print
"3",and
goto the test expression.
3
4.The test expression "printf("2")", that always true, so
print "2", and goto the for loop body expression.
2
5.the for loop body expression "return 0", the expression
"return 0" return '0' to the function main(),and end the
execution of the main(), But print nothing.
So, the output is:
32
End. Thanks!
This is the program:
#include<stdio.h>
int main()
{
int i=(-5);
while(i<=5){
if (i>=0){
break;
}
else{
i++;
continue;
}
printf("hello\n");
}
return 0;
}
My question is, why does 'hello' not get printed at all?
Because you have used continue incorrectly. It basically stops the line that is after it and goes to the condition checking part of the while loop. That's why it doesn't print hello.
From standard $6.8.6.2
A continue statement causes a jump to the loop-continuation portion of
the smallest enclosing iteration statement; that is, to the end of the
loop body.
You have a single if else statement. Everything that happens inside that loop will happen inside the if or the else. In your particular case, it will execute the else statement until 'i' is 0(the continue makes it so that it goes back to the loop condition, but in your case the continue is completely unnecessary because it's the last statement in the else), then it will execute the if and break out of the loop
Stepping though the loop, we have
1st pass i == -5, if condition false, else branch taken, i incremented to -4, continue to start of while loop
2nd to 4th pases same for i == -4 to i == -2
5th pass i == -1, if condition false, else branch taken, i incremented to 0, continue to start of while loop
6th pass i == 0, if condition true, break from while loop, return 0 from main
Neither of the if branches cause the flow to pass through the printf line.
The reason why printf() statement will never execute is because you had break statement in if and continue statement in else. Both statement are useful to break or skip the flow of execution of program.
Click here to learn when to use those statements.
Now, here i is initialized with -5. So until i reaches the value 0, else() part of the code will be executed. Else has continue statement, that will skip all the following statements and start next iteration. So, printf() statement will be skipped every time.
Once i will be incremented up to 0,if() part of code will be executed. If() has break statement that will break the loop and execution of the program will be over by main() returning 0 as there are no more statements following loop other than return 0.
Hope it'll be helpful.
My first question here on forum. I'm not sure why the output of the code is "hi" whereas I'm thinking it should be null. I might be missing here something badly. Help appreciated.
#include <stdio.h>
int main(void)
{
int i = 0;
while (i == 0)
{
printf("hi\n");
i++;
}
}
Your while loop will run what you have enclosed in it up until the stopping condition is false. you have int i = 0 as your starting value and your while loop condition says while (i == 0) to print "hi". Since i = 0, your condition is true one time and will print "hi" once before i increments and becomes false on the next pass.
The output of your code is correct, the while loop is entered because i == 0 and then i changes to 1 so the condition is false on the second iteration which makes the loop end and thus the program too.
You are confusing while loops with until loops (which C doesn't have). The while loop will execute its body while a condition is true, not until it is true. So if you want to print "hi" 10 times, you will need to write
int i = 1;
while (i <= 10) {
printf("hi\n");
++i;
}
#include <stdio.h>
int main(void)
{
int i = 0;
while (i == 0)
{
printf("hi\n");
i++;
}
}
while loop works in such a way that the loop executes only if the condition inside the parenthesis is true. In the above code, the value of 'i' is initially set to 0, which satisfies the condition of the while loop. It enters inside the loop, goes on to print 'hi' and then increments the value of 'i'.
Now the condition of while is again checked. Since the condition fails this time ,as the value of 'i' has been incremented, it exits out of the loop and the program terminates. I hope it answers your question.
like #iharob said, i==0 returns 1 which creates an infinite loop running and printing hi hi hi hi hi
if i was to do them, I would put in an if statement inside the while loop to check if i is still 0 or changed. if its 0, print hi, else, return 0;
it is obvious that the syntax that your are looking for is a do ... while loop
because programs run from up to down and left to right, the moment that your program reaches the while checks the i and it is still 0 but for the next loop it won't print anything because i=1.
I have a doubt about the for loop of the following code in C:
main()
{
int i=1;
for(;;)
{
printf("%d",i++);
if(i>10)
break;
}
}
I saw this code in a question paper. I thought that the for loop won't work because it has no condition in it. But the answer says that the code has no error. Is it true ? If true, how ?
The regular for loop has three parts:
Initialization
Condition
Increment
Usually they are written like this:
for (initialization; condition; increment) { statements }
But all three parts are optional. In your case, all parts are indeed missing from the for loop, but are present elsewhere:
The initialization is int i=1
The condition is if (i>10) break
The increment is i++
The above code can be equivalently written as:
for (int i=1; i <= 10; i++) {
printf("%d", i);
}
So all the parts necessary for a for loop are present, except they are not inside the actual for construct. The loop would work, it's just not a very readable way to write it.
The for (;;) loop is an infinite loop, though in this case the body of the loop takes actions that ensure that it does not run forever. Each component of the control is optional. A missing condition is equivalent to 1 or true.
The loop would be more clearly written as:
for (int i = 1; i < 11; i++)
printf("%d", i);
We can still debate whether the output is sensible:
12345678910
could be produced more easily with:
puts("12345678910");
and you get a newline at the end. But these are meta-issues. As written, the loop 'works'. It is syntactically correct. It also terminates.
You are not specifying any parameters or conditions in your for loop, therefore, it would be an endless loop. Since there is a break condition based on another external variable, it would not be infinite.
This should be re-written as:
for (int i = 1; i <= 10; i++)
printf("%d",i++);
It's an infinite loop. When there is not a condition in for and we use ;; the statements in the body of for will be executed infinitely. However because there is a break statement inside it's body, if the variable i will be greater than 10, the execution will be stopped.
As it is stated in MSDN:
The statement for(;;) is the customary way to produce an infinite loop which can only be exited with a break, goto, or return statement.
For further documentation, please look here.
Even if a for loop is not having any condition in it, the needed conditions are specified inside the for loop.
The printf statement has i++ which keeps on increasing the value of i and next we have if statement which will check if value of i is less than 10. Once i is greater than 10 it will break the loop.
Why does it tend to get into an infinite loop if I use continue in a while loop, but works fine in a for loop?
The loop-counter increment i++ gets ignored in while loop if I use it after continue, but it works if it is in for loop.
If continue ignores subsequent statements, then why doesn't it ignore the third statement of the for loop then, which contains the counter increment i++? Isn't the third statement of for loop subsequent to continue as well and should be ignored, given the third statement of for loop is executed after the loop body?
while(i<10) //causes infinite loop
{
...
continue
i++
...
}
for(i=0;i<10;i++) //works fine and exits after 10 iterations
{
...
continue
...
}
Because continue goes back to the start of the loop. With for, the post-operation i++ is an integral part of the loop control and is executed before the loop body restarts.
With the while, the i++ is just another statement in the body of the loop (no different to something like a = b), skipped if you continue before you reach it.
The reason is because the continue statement will short-circuit the statements that follow it in the loop body. Since the way you wrote the while loop has the increment statement following the continue statement, it gets short-circuited. You can solve this by changing your while loop.
A lot of text books claim that:
for (i = 0; i < N; ++i) {
/*...*/
}
is equivalent to:
i = 0;
while (i < N) {
/*...*/
++i;
}
But, in reality, it is really like:
j = 0;
while ((i = j++) < N) {
/*...*/
}
Or, to be a little more pedantic:
i = 0;
if (i < 10) do {
/*...*/
} while (++i, (i < 10));
These are more equivalent, since now if the body of the while has a continue, the increment still occurs, just like in a for. The latter alternative only executes the increment after the iteration has completed, just like for (the former executes the increment before the iteration, deferring to save it in i until after the iteration).
Your increment of i is after continue, so it never gets executed
while(i<10) //causes infinite loop
{
.........
continue
i++
......
}
In any loop, continue moves execution back to the top of the loop, not executing any other instructions after the continue statement.
In this case, the for loop's definition is always executed (per standard C), whereas the i++; statement is NOT executed, because it comes AFTER the continue statement.
Because the third part of the for is always executed.
continue statement jumps the control to the end of the statements in current iteration of loop i.e. it skips the execution of the statements in the current iteration and moves to the next iteration of the loop.
With while loop, continue statement causes control to reach the end of statements (including increment statement), thus causing loop to continue forever.
With for loop, continue statement jumps the control to end of statement and excutes the increment statement (In for loop, increment statement is considered seperate from the statments written within the body of the loop).
for loop holds condition statements and increment, so when the condition is satisfied it goes to execute the statement inside for loop,but if write continue statement than it will again reached to first line of for loop i.e. increment and checking of condition statement, if satisfied than again comes in for execution.
For while loop it just checks the condition statement and if condition satisfied it goes for the execution of statements in the while loop.
so continue will not execute any line after it.and hence your condition satisfied every time and goes for the infinite loop.
continue bypasses the rest of the block and begins again at the top of the block if the conditional of the loop is met.
The next question is: "What do I do, then?"
There are two answers I can think of.
Example:
void foo ()
{
size_t i = 0;
do
{
/*...*/
if ( /*...*/ )
{
/*...*/
continue;
}
/*...*/
i++;
} while ( /* loop conditional */ );
}
Solution #1: Manually Increment
void foo ()
{
size_t i = 0;
do
{
/*...*/
if ( /*...*/ )
{
/*...*/
i++;
continue;
}
/*...*/
i++;
} while ( /* loop conditional */ );
}
Solution #2: A uniquely valid application of goto*
void foo ()
{
size_t i = 0;
do
{
/*...*/
if ( /*...*/ )
{
/*...*/
goto foo_next;
}
/*...*/
foo_next:
i++;
} while ( /* loop conditional */ );
}
goto is valid in this case because incrementation in two places is technically the same instruction. This solution is especially relevant when the per-iteration-volatile variables are more complex; such as, setting multiple variables or modifying a value with an equation or function.
In the event of a single increment or decrement statement, Solution #1 may prove favorable; however, it should be noted that: if the code is modified after such an implementation, one must remember to update both instances of the statement (which may be prone to bugs, especially if the modifications take place after an extended period of time**). Therefore, I highly reccomend Solution #2.
*Some consider any and all use of goto bad practice. I recommend you decide for yourself, and leave you this: google for "c goto bad"
**A comment reminding of this necessity may suffice, but — if my advice has been followed — the per-iteration-volatile variables in are restricted to a single statement. And I quote:
There is never a reason to comment a single line
-Linus Torvalds (source: http://yarchive.net/comp/linux/coding_style.html)