+ 9

What is going here?

#include <iostream> using namespace std; int main() { int num; num = 5; num = num++; cout<<num; return 0; } // Output -> 5 Why????

7th Mar 2019, 8:36 AM
Ayush Sinha
Ayush Sinha - avatar
17 ответов
+ 8
What's the prblm
7th Mar 2019, 8:37 AM
Ayush Pandey
Ayush Pandey - avatar
+ 7
num = num++ means that the value of num is set to 5. The ++ doesn't get executed because of the value set.
7th Mar 2019, 8:41 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 7
cout<<num++; It instructs the code to first pass the variable to cout and then increase it's value Note:- ++ is at last cout<<++num; It instructs the code to first increase and then pass it to cout Note:- ++ is at first
7th Mar 2019, 5:35 PM
Shahil Ahmed
Shahil Ahmed - avatar
+ 6
// Please, use increment without using the assignment Correction : num++ |or| num += 1
7th Mar 2019, 8:43 AM
program
program - avatar
+ 6
Guys,I want to Know the logic behind this scenario... ⚡Prometheus ⚡ and // Zohir 🐍 .
7th Mar 2019, 8:47 AM
Ayush Sinha
Ayush Sinha - avatar
+ 6
Check out 2nd ans
7th Mar 2019, 8:48 AM
Ayush Pandey
Ayush Pandey - avatar
+ 6
See when we use num++ it increases the value of num by 1 later(as it is a suffix increment) . There for num++ is still 5 and when u assign it again Num=num++ the value 5 is stored which is not incremented again
7th Mar 2019, 8:50 AM
Ayush Pandey
Ayush Pandey - avatar
+ 6
~ swim ~ So is my ans not appropriate.
8th Mar 2019, 4:43 AM
Ayush Pandey
Ayush Pandey - avatar
+ 6
Num=num++ is a problem
11th Mar 2019, 8:40 PM
Sławek J.
+ 4
Try Num=num+1
7th Mar 2019, 8:45 AM
Ayush Pandey
Ayush Pandey - avatar
+ 3
i would suggest you to use a different variable to store the value after its incremented.so for example: num2=num++;
7th Mar 2019, 1:56 PM
umair
umair - avatar
+ 2
hey sorry just checked the code and it seems that storing it in different var wont work. here's the solution for your code: #include<iostream.h> using namespace std; int main(){ int num; num=5; num++; cour<<num; return 0; } output: 6
7th Mar 2019, 1:59 PM
umair
umair - avatar
+ 2
Because num++ is using post increment, Which has lower priority than assignment operator.
7th Mar 2019, 7:31 PM
Ashish Gupta
+ 2
Num++ first return a value the only it increment the value so the output does not get affect If you use ++num it first increment the value then only return the value
8th Mar 2019, 12:01 AM
Programmer Raja
Programmer Raja - avatar
+ 1
num++ means the value of num is first assigned to something and then incremented. But here, you assigned num to num, so the increment is lost. try ++num instead (first increase num by 1 and then assign it to something)
8th Mar 2019, 1:44 PM
kritomas
kritomas - avatar