Click here to Skip to main content
15,904,348 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to subtract sum of x and y from z and then increment it in a single statement in C++

What I have tried:

#include<iostream>
using namespace std;
int main()
{
	int x,y,z,p;
	x=5;
	y=6;
	z=20;
	p=(z-(x+y))++;
	cout<<"value of z="<<p;
}


it's showing error value required as left operand of assignment
Posted
Updated 6-Oct-17 6:46am
v2
Comments
David_Wimbley 6-Oct-17 12:12pm    
Your issue is likely with x+y=z++;. You probably need to go z=x+y; and then do z++ as z++ is not a variable, ++ is an operator and cannot be treated as part of the variable.

I don't know why you would need to implement in a single statement, seems pretty dumb to me but I guess you could do z = x + y + 1 or z = (x+y)++;. I didn't throw this into a compiler to see if it is valid as I wouldn't try to do a math operation and increment in the same line to begin with, this is probably a homework assignment and not a valid real world situation.
Member 13074487 6-Oct-17 12:16pm    
how can I perform all the operation in a single statement? I'm only allowed to use one statement to for calculation
David_Wimbley 6-Oct-17 12:16pm    
See revised comment
jeron1 6-Oct-17 12:18pm    
'How to subtract sum of x and y from z'
There's no subtraction in your code and
How can this be done if z is uninitialized?

Quote:
I've done this z=z-(x+y); but is it possible to increment it in the same line?????

No. You need what is called an lvalue - because the ++ operator is a "shortcut" operation which basically says "copy this variable, increment it by one, then use the value you remembered". You can only pre-or post fix increment (or decrement) a variable, not an result.

Basically, you are trying to get creative with the auto increment operators: don't. That way lies some really nasty problems. See here: Why does x = ++x + x++ give me the wrong answer?[^]
 
Share this answer
 
You need a single variable on the left side of an assignment.

Write the code first in separated statements:
z = z - (x + y); // Subtract sum of x and y from z; or z-= x + y
z = z + 1; // increment z; or z++
Think now how this can be put into one line.
Tip: Subtracting a negative number from a value is equivalent to adding the absolute value of the number.
 
Share this answer
 
Comments
Member 13074487 6-Oct-17 12:32pm    
I've done this z=z-(x+y); but is it possible to increment it in the same line?????
David_Wimbley 6-Oct-17 14:52pm    
z=(z-(x+y)) + 1;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900