Update statement in empty for loop - c++

A similar question has been answered here[https://stackoverflow.com/a/13421435/3276830 ]. The author says
The following code
for (i=0;i<5;i++);
{
printf("hello\n");
}
is interpreted as follows:
Repeat five times for (i=0;i<5;i++)
... do nothing (semicolon)
Open a new scope for local variables {
... Print "hello"
Close the scope }
However, for the following for loop
int i = 0;
for(;i++;cout<<i<<" ");
cout<<i<<" ";
The output I get is just 1, but I expected it to be 123456.....
Edit, I know the difference between prefix and postfix operation. But yeah I did miss that it was 0 the first time loop ran.

int i = 0;
for(;i++;cout<<i<<" ");
This loop can never execute because i is 0, so i++ evaluates to 0 (the value before incrementing it) which is false. Try ++i instead.

the
for(;;i++, cout<<i<<" ");
looks more aesthetically :) correct and will work no matter prefix or postfix

Related

C++ character variable value of '\x1'

I'm failing to understand why would the loop exit at the value of character variable i = '\x1'
#include <iostream>
using namespace std;
int main()
{
char i;
for (i = 1; i < 10, i++;)
{
cout << i << endl;
}
return 0;
}
Can somebody please explain this behavior ?
This is wrong
for (i = 1; i < 10, i++;)
/* ^ should be ; */
You only declared 3 regions for the loop, but put your increment statement in the middle area, and left your increment area empty. I have no idea which statement in the middle area your compiler will choose to execute. Best not to try to be cute and deceive your compiler. Let alone some colleague who will read your code years from now and go WTF???
A for loop has 3 distinct areas delimited by semi-colons:
The initialization area. You can declare as many variables in here as you want. These can be delimited by commas.
The test area. This is where an expression goes to test if the loop should continue.
The post loop area. This region of code gets executed after every loop.
Try to keep it simple. If it is going to be more complicated then use a while loop.
The reason that i ends up being 1 is that when i++ is zero, which terminates the loop, then i will become 1 (That is what the form of the ++ operator you used does). As the other answered have pointed out, once you fix your code by moving i++ out of the condition by replacing the comma with a semicolon, then i will make it all the way to 10 as desired.
for (i = 1; i < 10; i++)
You wrote for statement wrong.

Using cout inside an FOR loop

I tried testing the following code and found that the loop is never executed :
int i=0;
for(;i++;cout<<i)
{
if(i==5)
break;
}
I read the following post about the value returned by cout from the following post :
What's the difference between cout<<cout and cout<<&cout in c++?
But, I am unable to figure out why. Can someone help me with this.
int i = 0;
for (; i++; cout << i)
At the 1st loop, i++ is evaluated as 0 before increment happens and thus terminates the loop.
The first time the loop exit condition (i++) is checked, i's value is 0 (i.e. false). Hence it never enters the loop.
i++ is post increment. So i becomes 1 but the value which is checked in the loop exit condition is the value before increment - i.e. 0.

c++ code magically add 1 to the output

So I can't figure this out. (obviously)
Basically the variable count is declared in the beginning, then only modified or incremented in one place. The expected final count is 78682. And when count is equal to that, I'll print out the string "ok". When count is incremented to 78683, the code checks the condition and prints the string "not ok".
It never prints "not ok", but at the very end when we print the value of the count, it's 78683! When did c++ incremented?
Another thing is that when the comment is uncommented below, the final result then becomes 78682, though I just don't understand why. Anyone? (oh btw, the code takes a minute to run....)
#include <stdio.h>
int main(){
int count=0, sum=0;
int length []={1,2,4,10,20,40,100,200};
int value [] ={200,100,50,20,10,5,2,1};
int tmp[8] ={0};
bool stop=false;
while(!stop){
sum=0;
for(int j=0,k=0; j<8; j++){
sum+=value[j]*tmp[j];
if(j==7){
if(sum==200){
count++;
if(count==73682) printf("ok\n");
if(count==73683) printf("not ok\n");
}
k=j;
tmp[k]++;
while(tmp[k]==length[k]+1){
tmp[k]=0;
k--;
tmp[k]++;
if(tmp[0]==2)
{
//tmp[0]--;
stop=true;
}
}
}
}
}
printf("Total %d.", count);
return 0;
}
On my computer I getting
ok
Total 73682.
both with the line commented and with the line uncommented. Therefore I can't debug it.
But the most probable assumption is that the reason you get wrong result is out-of-bounds array access. If you write tmp[anything] it can be any place in memory, including the place where count is stored. So you need to check that 0 <= anything && anything < 8. You can such an access here:
while(tmp[k]==length[k]+1){
tmp[k]=0;
k--;
please add safety checks to ensure k >= 0.
P.S. I added the check:
while(tmp[k]==length[k]+1){
tmp[k]=0;
k--;
if( k < 0 ) printf("oops\n");
with the line commented I get
ok
oops
Total 73682.
with the line uncommented I get
ok
Total 73682.
so probably you have some other mistake in the program. Sorry, can't find it. (Also knowing what the program suppose to do you can print intermediate results and check them. But you should see out of bounds access on you computer if you get 73683).

For loop adding to a variable

I am trying to create a loop that adds 1 to a int variable every time the if statement is true
But while testing the code even though the if statement is true the variable is not incremented, as if the my for loop is not incremented at all....
Code sample:
int left_jab_count;
if(area >=100000 && area1 <100000)
{
cout<<"LEFT JAB HAS BEEN THROWN"" "<<area<<endl;
for(int left_jab_count = 0; left_jab_count < 0 ;++left_jab_count)
{
cout<<"Left Jab :"<<left_jab_count<<endl;
}
}
can anybody see where am going wrong here ?
for(int left_jab_count = 0; left_jab_count < 0 ;++left_jab_count)
//^^^^left_jab_count is never < 0
// change <0 to some value larger than 0
you for loop is never executed. Therefore, left_jab_count will never get incremented, you never enter the body of for loop.
Meanwhile, you declared left_jab_count twice.
tacp has adequately covered the issues with your current code, so I won't go into those. Based on your specification, "I am trying to create a loop that adds 1 to a int variable every time the if statement is true", what you want is something like this:
int left_jab_count = 0; // Don't forget to initialise this
while (true) // Replace with real loop
{
// Do NOT initialise left_jab_count here, otherwise it will be
// reset to 0 on every loop
// Insert code which changes area and area1
if (area >= 100000 && area1 < 100000)
{
cout << "LEFT JAB HAS BEEN THROWN " << area << endl;
left_jab_count++;
}
}
Unless you've misstated your specification, then you don't need a for loop inside the if block.
JBentley answered the question which was set by you. In the While statement that he posted you should add a condition which is true so that the code inside can run. I guess you want to enter:
while (left_jab_count < NUMBER)
Be sure to have a true condition so that the loop can start and run the if statement.

Post-increment and pre-increment within a 'for' loop produce same output [duplicate]

This question already has answers here:
Difference between pre-increment and post-increment in a loop?
(22 answers)
Closed 8 years ago.
The following for loops produce identical results even though one uses post increment and the other pre-increment.
Here is the code:
for(i=0; i<5; i++) {
printf("%d", i);
}
for(i=0; i<5; ++i) {
printf("%d", i);
}
I get the same output for both 'for' loops. Am I missing something?
After evaluating i++ or ++i, the new value of i will be the same in both cases. The difference between pre- and post-increment is in the result of evaluating the expression itself.
++i increments i and evaluates to the new value of i.
i++ evaluates to the old value of i, and increments i.
The reason this doesn't matter in a for loop is that the flow of control works roughly like this:
test the condition
if it is false, terminate
if it is true, execute the body
execute the incrementation step
Because (1) and (4) are decoupled, either pre- or post-increment can be used.
Well, this is simple. The above for loops are semantically equivalent to
int i = 0;
while(i < 5) {
printf("%d", i);
i++;
}
and
int i = 0;
while(i < 5) {
printf("%d", i);
++i;
}
Note that the lines i++; and ++i; have the same semantics FROM THE PERSPECTIVE OF THIS BLOCK OF CODE. They both have the same effect on the value of i (increment it by one) and therefore have the same effect on the behavior of these loops.
Note that there would be a difference if the loop was rewritten as
int i = 0;
int j = i;
while(j < 5) {
printf("%d", i);
j = ++i;
}
int i = 0;
int j = i;
while(j < 5) {
printf("%d", i);
j = i++;
}
This is because in first block of code j sees the value of i after the increment (i is incremented first, or pre-incremented, hence the name) and in the second block of code j sees the value of i before the increment.
The result of your code will be the same. The reason is that the two incrementation operations can be seen as two distinct function calls. Both functions cause an incrementation of the variable, and only their return values are different. In this case, the return value is just thrown away, which means that there's no distinguishable difference in the output.
However, under the hood there's a difference: The post-incrementation i++ needs to create a temporary variable to store the original value of i, then performs the incrementation and returns the temporary variable. The pre-incrementation ++i doesn't create a temporary variable. Sure, any decent optimization setting should be able to optimize this away when the object is something simple like an int, but remember that the ++-operators are overloaded in more complicated classes like iterators. Since the two overloaded methods might have different operations (one might want to output "Hey, I'm pre-incremented!" to stdout for example) the compiler can't tell whether the methods are equivalent when the return value isn't used (basically because such a compiler would solve the unsolvable halting problem), it needs to use the more expensive post-incrementation version if you write myiterator++.
Three reasons why you should pre-increment:
You won't have to think about whether the variable/object might have an overloaded post-incrementation method (for example in a template function) and treat it differently (or forget to treat it differently).
Consistent code looks better.
When someone asks you "Why do you pre-increment?" you'll get the chance to teach them about the halting problem and theoretical limits of compiler optimization. :)
This is one of my favorite interview questions. I'll explain the answer first, and then tell you why I like the question.
Solution:
The answer is that both snippets print the numbers from 0 to 4, inclusive. This is because a for() loop is generally equivalent to a while() loop:
for (INITIALIZER; CONDITION; OPERATION) {
do_stuff();
}
Can be written:
INITIALIZER;
while(CONDITION) {
do_stuff();
OPERATION;
}
You can see that the OPERATION is always done at the bottom of the loop. In this form, it should be clear that i++ and ++i will have the same effect: they'll both increment i and ignore the result. The new value of i is not tested until the next iteration begins, at the top of the loop.
Edit: Thanks to Jason for pointing out that this for() to while() equivalence does not hold if the loop contains control statements (such as continue) that would prevent OPERATION from being executed in a while() loop. OPERATION is always executed just before the next iteration of a for() loop.
Why it's a Good Interview Question
First of all, it takes only a minute or two if a candidate tells the the correct answer immediately, so we can move right on to the next question.
But surprisingly (to me), many candidates tell me the loop with the post-increment will print the numbers from 0 to 4, and the pre-increment loop will print 0 to 5, or 1 to 5. They usually explain the difference between pre- and post-incrementing correctly, but they misunderstand the mechanics of the for() loop.
In that case, I ask them to rewrite the loop using while(), and this really gives me a good idea of their thought processes. And that's why I ask the question in the first place: I want to know how they approach a problem, and how they proceed when I cast doubt on the way their world works.
At this point, most candidates realize their error and find the correct answer. But I had one who insisted his original answer was right, then changed the way he translated the for() to the while(). It made for a fascinating interview, but we didn't make an offer!
Hope that helps!
Because in either case the increment is done after the body of the loop and thus doesn't affect any of the calculations of the loop. If the compiler is stupid, it might be slightly less efficient to use post-increment (because normally it needs to keep a copy of the pre value for later use), but I would expect any differences to be optimized away in this case.
It might be handy to think of how the for loop is implemented, essentially translated into a set of assignments, tests, and branch instructions. In pseudo-code the pre-increment would look like:
set i = 0
test: if i >= 5 goto done
call printf,"%d",i
set i = i + 1
goto test
done: nop
Post-increment would have at least another step, but it would be trivial to optimize away
set i = 0
test: if i >= 5 goto done
call printf,"%d",i
set j = i // store value of i for later increment
set i = j + 1 // oops, we're incrementing right-away
goto test
done: nop
If you wrote it like this then it would matter :
for(i=0; i<5; i=j++) {
printf("%d",i);
}
Would iterate once more than if written like this :
for(i=0; i<5; i=++j) {
printf("%d",i);
}
Both i++ and ++i is executed after printf("%d", i) is executed at each time, so there's no difference.
You could read Google answer for it here:
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Preincrement_and_Predecrement
So, main point is, what no difference for simple object, but for iterators and other template objects you should use preincrement.
EDITED:
There are no difference because you use simple type, so no side effects, and post- or preincrements executed after loop body, so no impact on value in loop body.
You could check it with such a loop:
for (int i = 0; i < 5; cout << "we still not incremented here: " << i << endl, i++)
{
cout << "inside loop body: " << i << endl;
}
The third statement in the for construct is only executed, but its evaluated value is discarded and not taken care of.
When the evaluated value is discarded, pre and post increment are equal.
They only differ if their value is taken.
Yes, you'll get exactly same outputs for both. why do you think they should give you different outputs?
Post-increment or pre-increment matters in situations like this:
int j = ++i;
int k = i++;
f(i++);
g(++i);
where you provide some value, either by assigning or by passing an argument. You do neither in your for loops. It gets incremented only. Post- and pre- don't make sense there!
There is a difference if:
int main()
{
for(int i(0); i<2; printf("i = post increment in loop %d\n", i++))
{
cout << "inside post incement = " << i << endl;
}
for(int i(0); i<2; printf("i = pre increment in loop %d\n",++i))
{
cout << "inside pre incement = " << i << endl;
}
return 0;
}
The result:
inside post incement = 0
i = post increment in loop 0
inside post incement = 1
i = post increment in loop 1
The second for loop:
inside pre incement = 0
i = pre increment in loop 1
inside pre incement = 1
i = pre increment in loop 2
Compilers translate
for (a; b; c)
{
...
}
to
a;
while(b)
{
...
end:
c;
}
So in your case (post/pre- increment) it doesn't matter.
EDIT: continues are simply replaced by goto end;