changing variable values with unary vs arithmetic operators
wondering if anyone can explain why unary ops vs, arithmetic ops affect variables in main() in different ways in the following function call:
Code:
#include <stdio.h> |
Quote:
|
changing variable values with unary vs aritmetic operators
Pam;
What is unclear is, I thought, already stated in the code comments. Why is it that val a, originally initialized =0, is NOT changed to val a = 1 in main() (a is still = 0), but if passed as a++, the value is incremented in main() to val a = 1? |
a+1 will return with the value a+1 and will not modify a.
a++ will return the original value of a and will increment a afterwards. This is how c works, this is the syntax. so in displayParam(a+1); 1 will be used and a will remain 0, in displayParam(a++); 0 will be used and after the call to displayParam a will be incremented. unary operator usually modifies the variable, binary operators usually take only the values and leave the variables intact. |
Quote:
|
Thanks to both Pan64 & Johnsfine for the quick replies.
It seems strange that instructional manuals always seem to state that a++ is a simple equivalent of a+1, yet there is such an obvious difference in the way they actually operate that they neglect to point out! |
Quote:
That is an unlikely error for any C manual. Are any of the manuals that you think said that online? If you provide a link, someone may be able to explain what the text really means. |
Quote:
|
RE: reply by johnsfine
yes, suicidaleggroll's comment is more explicit than what I wrote (but is exactly what I meant). As he mentioned, I now realize that it is "more or less correct (at least when it's used on its own line and not embedded in some other call)." It's the part about being embedded in some other call that confused me. |
Actually, re '++' it depends when you use it
Code:
# this is pre-increment and affects a before its used in a calc You should play around with these to get it clear in your head; see also 'a+=1'. |
All times are GMT -5. The time now is 10:47 PM. |