4️⃣

3.4 Assignment Operators

 

Assignment Operators

Assignment operators are used to change the values of variables. The chart below contains the different types of assignment operators you can use in C:
 

Increment

 
There is a shortcut in coding for incrementing by 1, or adding 1 to the value of a variable. This is equivalent to using the second assignment operator on the chart with a value of 1 (a += 1). Instead of having to type “+= 1”, you can just use “++”. Examples:
 
int num = 9; num += 1; // The second line of code adds 1 to num, meaning that its value is now 10.
 
int num = 9; num++; // The second line of code is another, shorter way of adding 1 to num, // meaning that its value is now 10.
 

Decrement

Like with incrementing, there is also a shortcut in coding for decrementing by 1, or subtracting 1 from the value of a variable. This is equivalent to using the third assignment operator on the chart with a value of 1 (a -= 1). Instead of having to type “-= 1”, you can just use “--”. Examples:
 
int num = 9; num -= 1; // The second line of code subtracts 1 from num, meaning that its value is now 8.
 
int num = 9; num--; // The second line of code is another, shorter way of subtracting 1 from num, // meaning that its value is now 8.
 

Previous Section

Next Chapter

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.