I just started programming in C, and while practicing with for loops, I came up with the following piece of code:
#include <stdio.h>
int main()
{
int x;
for (x=0;x=10;x=x+1)
printf("%d\n",x);
return 0;
}
When I run the code, I fall into an infinite loop. In my C manual it says that the condition x =10 is always true, but I can't get my head around it. If I give the variable x a value of 0 at the beginning, should the for loop not even start, or when the value of x reaches 10, shouldn't the loop stop?
Thanks in advance!
The condition part of your for loop is wrong. What you are doing is :
for (x = 0; x = 10; x = x +1) {
// Operations
}
The condition you have got here is x = 10 which is an affectation. So x = 10 will return 10, which also means true. Your for loop is equivalent to :
for (x = 0; true; x = x + 1) {
// Operations
}
This is why you have got an infinite loop, you should replace the affectation operator = by the comparason one with two equals sign ==. This means the for will loop while x is equals to 10.
EDIT : As Virgile mentioned in comments, for the second for loop, x will go from 0 to INT_MAX, then the behavior is undefined. So, your code is more likely to look like :
for (x = 0; true; x = 10) {
// Operations
}
When entering a for loop, the initialization part is performed first. So after the loop initialization x is 0.
Before entering the body of the loop, even the first time, the condition is checked. The "condition" in this case does not compare x to 10 but sets it to 10 since you are using = instead of ==.
Since an assignment as an expression has the value of the variable after assignment, the conditional expression has a value of 10 since that is what was assigned to x. Because this value is non-zero, it evaluates to true, and always will.
The problem here is, Take a close look on the condition part(2), in this what x=10, means is it is just assigning the value 10 to x, and it returns "True" always, so no problem what you have incrementing, it comes to 10 always, Thus infinite loop.
What you are trying to do is, you are implicitly converting int to bool in this line:
for (x=0;x=10;x=x+1)
^^^^
here, x=10; results true
So, it prints 10 everytime as you are using the = assignment operator.
for(int x=0;true;x=x+1)
What you could do to maintain the loop?
Use relational operators:
for (x=0;x!=10;x=x+1)
for (x=0;x==10;x=x+1)
for (x=0;x<10;x=x+1)
Related
So I've seen this used before some of my profs code aswel as in some of my friends who have more experience with programming.
int number = 0;
while(number) {
a bunch of code
}
My understanding is that this while loop is essentially running with no condition, i feel like it should be
while(number = 0) {
Isnt this essentially creating an infinite loop? but in the cases I've seen it used it can break out of the loop somehow.
edit:
do while that uses the argument in question. Note that the 2 functions being called in the switch case will call searchpatientdata again once they have completed.
This code is not currently wokring, but was working in a previous build and this function was the same. They also do not change the selection variable either.
The condition in a while loop can be any expression of scalar (numeric or pointer) type. The condition is treated as false if the result of evaluating the expression is equal to zero, true if it's non-zero. (For a pointer expression, a null pointer is equal to zero).
So while (number) means while (number != 0).
As a matter of style, I prefer to use an explicit comparison unless the variable is logically a Boolean condition (either something of type bool or _Bool, or something of some integer type whose only meaning values are true and false) -- but not everyone shares my opinion, and while (foo) is a very common way to write while (foo != 0).
The same applies to the condition in an if, a do-while, or a for statement.
Note that in your example:
int number = 0;
while(number) {
// a bunch of code
}
the body of the loop will never execute, because number is equal to zero when the loop is entered. More realistically, you might have:
int number = some_value;
while (number) {
// a bunch of code *that can change the value of number*
}
Any place in C where a Boolean value is required, any number will be evaluated like this:
zero → false
not zero → true
From C reference
Executes a statement repeatedly, until the value of expression becomes equal to zero. The test takes place before each iteration.
How it works?
entry control loop
condition is checked before loop execution
never execute loop
if condition is false there is no semicolon at the end of while
statement
Come to point as per OP's question yes
While (Variable_name) evaluated as True
In below Example While loop executes until condition is true
Example:
#include <stdio.h>
#include <stdbool.h>
int main(void)
{
int num=1;
while(true)
{
if(num==5)
{
break;
}
printf("%d\n",num);
num++;
}
return 0;
}
So I saw this in my text book and I cannot understand how it works.
x=0;
int i = 0;
int n;
while(!x && i < n){
if(array[i]==target)
x=1;
else
++i;
}
what I don't understand is how "!x" works in loop's condition.
what I understand is this loop keeps running until it runs n times or when array[i]==target, which will change the value of x = 0 to x = 1 and stop the loop.
what I tried:
I tried replacing !x to x==0 and it did the same job.
The short answer here is that it does not matter what !x is because it is surrounded with undefined behavior completely nullifying its effect.
In the statement
While(condition) {...}
condition must resolve to either true or false, and must therefore be logical expression.
Given:
int x=0;//This answer assumes 'int' here as not specified in OP
int i = 0;
int n;
while(!x && i <n)
Because x is initialized as 0, equivalent to false the expression !x resolves to true, satisfying part of the condition.
Because n is not initialized however, the condition (!x && i <n) invokes undefined behavior, making the results of the overall condition unknown at the time of first entry, i.e. it can be either true or false. Further more, n does is never modified within {...}, so if the initial path happens to enter the brackets, the condition will change only due to changes in i. But again, because the value of n is not known, only undefined behavior will occur.
I don't know what language this is but !someVar is typically shorthand syntax for "variable is false", or another way of writing someVar == false. And in binary 0 is false and 1 is true. In the C language, 0 is false and anything not 0 is true. Therefore, in your loop, while !x is shorthand syntax for while x == false or while x == 0. Again, generally speaking since we don't know the language.
While(!x) means if x is a condition then we go into the while loop, only if the condition does not satisfy.Here in your code you have assigned x as zero,so !x means 1 because '!' Basically means opposite if x =0 then !x =1, if x=1 then !x=0 (all numbers greater than 1 are also considered as 1 only) so while(1 && i<n) is what happening here in the next step.If i<n is true then you will enter into the loop. If i<n is false the you won't enter the loop.
while(!x)
{
intructions;
}
means that your instructions will only keep running over and over again if x is false or equals 0 and will stop executing instructions once x becomes true or different from 0
This question already has answers here:
What is the difference between ++i and i++?
(20 answers)
Closed 7 years ago.
I was toying with the concept of array pointers. I wrote this simple program:
#include <stdio.h>
int main (int argc, char **argv){
char s[] = "Hello world!\n";
char *i;
for (i = s; *i; ++i){
printf(i);
}
return 0;
}
which gives the very amusing output:
Hello world!
ello world!
llo world!
lo world!
o world!
world!
world!
orld!
rld!
ld!
d!
!
When I wrote this, however, I was under the impression that the output would start from the second row. Reason being, in the for loop, I use a pre-increment notation. i is set to the beginning of s, the Boolean condition is checked and it holds true, then i gets incremented and the block executes.
That was my impression, but obviously it is erroneous as the block executes before i gets incremented. I rewrote the program using a post-increment notation and got exactly the same result which confirms my hypothesis. If that is the case, then how are they treated differently in this program?
for (initialization; condition; increase) statement;
This for works in the following way:
initialization is executed. Generally, this declares a counter variable, and sets it to some initial value. This is executed a single time, at the beginning of the loop.
condition is checked. If it is true, the loop continues; otherwise, the loop ends, and statement is skipped, going directly to step 5.
statement is executed. As usual, it can be either a single statement or a block enclosed in curly braces { }.
increase is executed, and the loop gets back to step 2.
the loop ends: execution continues by the next statement after it.
There is no difference between postincrement and preincrement because increase is executed separately anyway.
The increment expression of the for loop is executed after the body. For your case
for (i = s; *i; ++i){
printf(i);
}
is similar to
i = s; // loop init
while (*i) // loop condition
{
printf(i);
++i; // loop increment
}
i is set to the beginning of s, the Boolean condition is checked and it holds true, then i gets incremented and the block executes.
Not quite. The actual syntax is
i is set to the beginning of s
the Boolean condition is checked
2.1. if it holds true the block executes,
2.2. come out of loop otherwise.
then i gets incremented and continue to step 2.
Note: In this particular scenario, pre and post increment to i are not going to make any difference.
the equivalent of
for( a ; b ; c )
{
statements
}
is
a ;
while( b )
{
statement
c ;
}
and
++i ;
i++ ;
are the same things, because i is only evaluated and the evaluation isn't used
Reason being, in the for loop, I use a pre-increment notation. i is set to the beginning of s, the Boolean condition is checked and it holds true, then i gets incremented and the block executes.
No. i is incremented after the block executes.
I rewrote the program using a post-increment notation and got exactly the same result which confirms my hypothesis. If that is the case, then how are they treated differently in this program?
They're not. Post-increment or pre-increment isn't going to make a blind bit of difference. The difference between those two is in the result of the expression i++, ++i (namely, will it evaluate to the previous value or to the new value?). It does not magically alter the entire flow of an encapsulating control structure. The evaluated result of the increment expression is just thrown away so it doesn't matter what you do as long as you provide an expression that results in incrementing i.
It's like how this:
int main()
{
int x = 5;
int y = 5;
int a = x++;
int b = ++y;
}
will result in different values for a and b because the result of the increment expression is used, whereas the following programs:
int main()
{
int x = 5;
x++;
}
int main()
{
int x = 5;
++x;
}
are identical.
i gets incremented after the block get executed.
Try this:
for(int i = 0; i < 5; ++i )
{
printf("\n %d",i);
}
can anyone explain the working of the for loop in the following code:
#include<stdio.h>
#include<conio.h>
int main()
{
char i=0;
for(i<=5&&i>=-1;++i;i>0)
printf("%d\n",i);
getch();
}
Let's break the for statement down, we have three phases, the initialiser, the test, and the modifier:
for(<Initialiser>; <Test>; <Modifier>)
<content>;
In your case:
for(i<=5&&i>=-1;++i;i>0)
// initialiser: i<=5&&i>=-1;
// test: ++i;
// modifier: i>0
The initialiser is done first. Here no assignment is done. Two boolean expressions (denoted by the >= and <= operators are compared in a logical &&. The whole initialiser returns a boolean value but it doesn't do anything. It could be left as a blank ; and there would be no change.
The test uses the pre-increment operator and so returns the result of i+1. If this result is ever 0 it evaluates as false and the loop will terminate. For any non-zero value it evaluates to true and continues. This is often used when i is initialised to a value less than zero and so the test will increment i until i+1 results in a zero, at which point the loop terminates.
Finally we have the modifier, which in this case simply uses the > operator to evaluate to a boolean value. No assignment is done here either.
The fact is that you've gotten the test and the modifier confused and put them in the wrong positions but before we sort that out let's see how it would work…
We begin with:
char i = 0;
…and for all intents and purposes this does the same thing as our for loops initialiser would do in normal circumstances. The next thing to be evaluated is the for loop's initialiser:
i<=5 && i>=-1;
Because i is 0 it is less-than-or-equal-to 5 and it is greater-than-or-equal-to -1. This expression evaluates to 1 but nothing is done with that value. All we've done is waste a bit of time with an evaluation.
Next up is the modifier to test whether or not the for loop's inner block should be executed:
++i;
This evaluates to 1 and also assigns that value to i. Now, as it's evaluated to a non-zero number, the loop executes:
printf("%d\n",i);
And the digit 1 is printed to the screen... Now it's the modifier that gets executed:
i>0
Well, i is 1 so that is greater-than 0. This evaluates to 1 (or true). Either way, this is ignored. The purpose of the modifier isn't to test or check anything. It's there so that you can change the state of the program each time the for loop iterates. Either way, the loop repeats and it will do this for a very long time. Why? Because ++i is going to evaluate to a non-zero number for a while. Whether or not it will ever terminate depends on how your system deals with integer overflows.
This is what you meant to do:
#include<stdio.h>
#include<conio.h>
int main()
{
for(char i=0; i<=5&&i>=-1; ++i)
printf("%d\n",i);
}
Do you see the difference? Our initialiser now starts the loop with the state of i as zero. We then test if it's within the bounds of -1 to 5 and each time we iterate we increment i by 1. This loop will output:
0
1
2
3
4
5
This snippet:
for(i<=5&&i>=-1;++i;i>0)
printf("%d\n",i);
Does the same as this:
i<=5 && i>=-1; //statement with no effect
while(++i)
{
printf("%d\n",i);
i>0; //statement with no effect
}
So, it's going to print i until ++i evaluates to 0. This will happen after i overflows and becomes negative, then incrementing towards 0. That will take 255 iterations to happen, since chars can store up to 256 different values.
for ( variable initialization; condition; variable update ) {
}
the variable initialization phase is done only once when the for loop starts.
the condition is checked everytime before running code inside the loop. if the condition is false then the loop is exited.
the variable update is done after the first iteration, from the second iteration it is done before the condition check.
Today I made a typo, and then found below code can be compiled successfully:
#include <stdio.h>
int main()
{
int i;
for (i=0;1,2,3,4,5;i++)
printf("%d\n", i);
}
I don't understand why
1,2,3,4,5
can be treated as a condition?
Your for condition is the expression 1,2,3,4,5. This expression is evaluated using C's comma operator and yields 5. The value 5 is a valid boolean expression that is true, therefore resulting in an infinite loop.
You are using the comma operator. The value of 1, 2, 3, 4, 5 is 5.
More generally, the value of a, b is b. Also, the value of f(), g() is the return value of g(), but both subexpressions f() and g() are evaluated, so both functions are called.
Yes. As others say it's .always true and the comma operator yields 5, hence the loop will repeat infinite times
You can verify it by replacing 5 with 0 . Like this 1,2,3,4,0
Here 0 is false, hence the condition fails.
Yes, 1,2,3,4,5 can be treated as a condition.
The output of 1,2,3,4,5 is 5.
In fact, you need not specify any condition in for loop.
for(;;) is a valid syntax.
A for loop:
for( E1; E2; E3 )
IB
with expressions E1, E2, E3 and an instruction IB is equivalent to a while loop:
E1;
while( E2 )
{
IB;
E3;
}
The only exception is E2, which must be present in while loop condition whilst may be omitted in a forloop condition (and then it is considered equal 1).
So, as others already said, your 1,2,3,4,5 is a comma expression equivalent to a constant 5, making the loop looping infinitely.
See that this code runs... but the for loop continues indefinitely. The condition 1,2,3,4,5 is always verified.
The compiler accepts more that one conditions in for loops. For example:
for(i=0, j=0; i<X, j>y; i++, j--)
//.....
So 1,2,3,4,5 are five conditions (not one) and all these conditions are verified (in fact, these numbers are all different from 0 so they're always true).
// try to know the meaning of condition.
#include <stdio.h>
int main()
{
int i=0;
if(i<=5) // try this
{
printf("%d\n",i);
i++; // increment i
}
}