Hello. I have this program from a list which the teacher gave us. Why this program doesnt show anything when is runned ? What it supposed to be the output ?
1 2 3 4 5 6 7 8 9 10 11 12 13
#include<iostream>
usingnamespace std;
int main(){
int i=5;
int t=2;
while(i<=8)
{
i=i++;
t=t+i;
}
cout<<t;
return 0;
}
Does the output gona be just "i=i++" cause the condition is true ?
Haw this program should be write to work ?
Sry my English brothers .
i=i++ was undefined before C++17, but now it will leave i unmodified because i++ returns the value of i before i was incremented which means you are essentially doing:
1 2 3
int oldValue = i;
i++; //increment
i = oldValue; // restore
Your English is ok, alas the program the teacher gave you is not. I assume your task is to find errors and traps.
i) if you compile it, you got no error from the compiler? (Regard warnings also as errors, as there may be a differnt point of view on the code.) On http://cpp.sh/ I am told:
In function 'int main()':
8:10: warning: operation on 'i' may be undefined [-Wsequence-point]
ii) you may simplify line 9 (and merge what line 8 intention probably is)
I suggest:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include<iostream>
usingnamespace std;
int main()
{
int i=5;
int t=2;
while(i<=8)
{
// i=i++; <<=== not very useful
t+=++i; // ++i, not i++ in that case (important)
}
cout<<t;
// return 0;
}
Edit: ++i increments i before its value is used in that clause/line/function/context, with i++ its value is used and then incremented, afterwards.
THANK YOU ALL !!!!!!!!!! Is a list from a test , i think i heard the teacher we will have TRAP exercises as well. Yea , is a trap exercise , i supposed to show him on test what is the mistake