Using the return value of a statement

118 views Asked by At

I want to know if it is possible to use the return value of a statement in C.

For example: If I start with a=0; then I know that the expression a++ will return 0 while a+=1 will return 1. But talking about statements, is there any semantic difference between a++; and a+=1;?

At first, they both look like they have similar behavior and, so, the only difference could be the existence of a way of using the return values of statements. Is it possible?

2

There are 2 answers

4
Potatoswatter On BEST ANSWER

Statements don't have return values. Expressions have values (unless of type void). Some expressions also have side effects.

a++ has a value equal to the original value of a and a+=1 has a value of one greater than the original value of a.

Assigning a new value to a is a side effect. Both expressions have the same side effect.

There's nothing more complicated about any of this. Do note though, that depending on a side effect within the same statement (not just the same subexpression) produces undefined behavior, unless there is a sequence point. Multiple side effects within the same statement, and side effect dependencies, are a more advanced topic so it is better to keep assignment statements simple.

3
Glenn Teitelbaum On

You want to compare ++a and (a+=1) which will both return 1

a++ means return the old value and then change a

++a means add one to a, and return the new value

(a+=1) means add one to a and return the new value (but technically it can be slower)

On its own line, ++a, a++ and a+=1 are all the same thing

if you call: foo(a++) and foo(a+=1) foo will be passed the different values.

Technically ++a can be faster than a+=1, but any level of optimization should result in the same thing