+ 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????
17 Réponses
+ 8
What's the prblm
+ 7
num = num++ means that the value of num is set to 5. The ++ doesn't get executed because of the value set.
+ 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
+ 6
// Please, use increment without using the assignment
Correction :
num++ |or| num += 1
+ 6
Guys,I want to Know the logic behind this scenario...
⚡Prometheus ⚡ and // Zohir 🐍 .
+ 6
Check out 2nd ans
+ 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
+ 6
~ swim ~ So is my ans not appropriate.
+ 6
Num=num++ is a problem
+ 4
Try
Num=num+1
+ 3
i would suggest you to use a different variable to store the value after its incremented.so for example:
num2=num++;
+ 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
+ 2
Because num++ is using post increment, Which has lower priority than assignment operator.
+ 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
+ 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)