Help : Simple Program Not Working

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>
using namespace 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 


You probably meant to write one of the following:
1
2
3
4
i = i + 1;
i += 1;
++i;
i++;
(they all accomplish the same thing)
Last edited on
1
2
3
4
5
while(i<=8)
{
    i=i++;
    t=t+i;
}


This i=i++; is bad.

This can work like this:

i begins at 5.
i++ returns 5, so i=i++ is i = 5

So the code is effectively this:

1
2
3
4
5
while(i<=8)
{
    i=5;
    t=t+i;
}


and that will loop forever.

You can see this for yourself by adding logging. Run this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream>
using namespace std;
int main(){
int i=5;
int t=2;
while(i<=8)
{
    i=i++;
    cout "i=" << i << " ";
    t=t+i;
}
cout<<t;
return 0;
}


Last edited on
Sry my English brothers

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>
using namespace 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.
Last edited on
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
Topic archived. No new replies allowed.