C: Operators - Assignment Operators
(Page 4 of 4 )
We've been working with an assignment operator for a while now, namely the “=” operator. An example would be assigning a value to a variable: int yourWeight = 400. We can also do this: a = a+1. This will add one to the value of a. Let's say we have two variables, a and b. Variable a will hold the value of ten, and variable b will hold the value of 5. If we write a= a+b, the new value of a is 15. We can also do this using shorthand methods, like the examples below. For instance, if we typed a+=b, we would still get the result of 15, without having to write a little extra code.
Here is a table of examples of shorthand operators:
Simple Assignments | Shorthand Assignments |
a=a +2 | a+=2 |
a=a-1 | a-=1 |
a=a*(9+2) | a*=(9+2) |
a=a/(9+2) | a=/(9+2) |
a=a % 9 | a %= 9 |
Here is some code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int myIQ = 150;
int yourIQ = 12;
printf("My IQ is %i... I laugh at your puny IQ!n",myIQ);
myIQ+=yourIQ;
printf("Our combined IQ is %i...",myIQ);
return(0);
}
This code results in:
My IQ is 150...I laugh at your puny IQ!
Our combined IQ is 162...
Incremental/Decremental Operators
Used in For and While Loops, the incremental/decremental operators add or subtract the value of a variable by 1, respectively. Depending upon where you place the operator, the value will either be incremented/decremented after or before the statement is evaluated. This might not make sense at the moment, but it will soon.
Consider this statement:
mysalary = 40000;
salaryafterraise = ++mysalary;
This is known as a prefix. In the above example, the value of both mysalary and salaryafterraise would be 40001. This is because the program adds 1 to the variable mysalary PRIOR to adding mysalary to salaryafterriase.
If I had written:
mysalary = 40000;
salaryafterraise = mysalary++;
Then the value of salaryafterraise would be 40000 and the value of mysalary would be 40001. This is because when we add the incrementer post fix, it adds mysalary to salaryafterraise, then increases the value of mysalary by one.
Well that's it for this episode. We still have some more operators to cover, and we will do so in the next article, alongside the array and commenting in C. So come back often.
Till then...
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |