The C language is full of shortcuts, and they're wonderful things. First, they save you typing time. More importantly, the shortcuts let you express some ideas in quick yet fun and cryptic ways, which is okay; C programmers can still read your code — no problem.
Two common C shortcuts are ++ and --, which are used for incrementing (adding one to) and decrementing (subtracting one from), respectively.
Incrementing with ++
Often in programming, you come across a situation where a value needs to be incremented: Whatever the value is, you have to add 1 to it. This happens a lot in loops, but it can occur elsewhere in programs as well.
For example, you have variable count and you need to add 1 to its value. You can do it like so:
count = count + 1;
Because C works out the math first, the current value of count is incremented by 1. Then that new value is stored in the count variable. So, if count now equals 6, count + 1 results in 7, and 7 is then stored back into the count variable. count then equals 7.
But you can build the code more compactly like this:
count++;
The ++ operator tells the computer to increment the value of count by 1. Whatever the value of count was, it's now one greater, thanks to ++. Here's a demo program:
#include <stdio.h>
int main()
{
int age;
printf("Enter your age in years:");
scanf("%d",&age);
printf("You are %d years old.\n",age);
age++;
printf("In one year you'll be %d.\n",age);
return(0);
}
Type this into your editor, save the source code to disk, compile, and run. You should see this prompt:
Enter your age in years:
If you enter 24 (which is generally a good age to be), your program will return the following:
You are 24 years old.
In one year you'll be 25.
The value of the variable age is changed by age++. That's incrementation!
Decrementing with --
To keep the world in harmonic balance, a -- operator counters the ++ operator in C. It decrements, or subtracts 1, from the variable it modifies. For example:
count--;
This statement subtracts one from the value of variable count. It's the same as
count = count - 1;
You can make just a couple changes to the previous source code to see -- in action:
#include <stdio.h>
int main()
{
int age;
printf("Enter your age in years:");
scanf("%d",&age);
printf("You are %d years old.\n",age);
age--;
printf("One year ago, you were %d.\n",age);
return(0);
}
Notice the changes in both Line 10 and 11. Save, compile, and run. If you again enter 24 as your age (and wouldn't we all like to stay at 24?), you should get this result:
You are 24 years old.
One year ago, you were 23.
dummies
Source:http://www.dummies.com/how-to/content/incrementing-and-decrementing-in-the-c-language.html
No comments:
Post a Comment