Increment And Decrement Operators In C With Precedence (+Examples)
The C language is a powerful and widely used programming language that offers various tools and features. They empower developers to write concise and efficient code, and one such tool/ fundamental programming concept is operators. There are multiple types of operators, such as arithmetic (addition, multiplication, division operators, etc.), bitwise, logical, relational, assignment operators, etc. In this article, we will discuss a specific type of operators, i.e., the increment and decrement operators in C.
These operators in programming play a crucial role in the manipulation of variables, evaluation of expressions, and determining the flow of a program. Understanding how the different forms of increment operators and decrement operators work is fundamental for any C programmer, as they contribute to both code readability and performance optimization. In this article, we will delve into the intricacies of these operators, their functionality in complex expressions, and best practices in C programming.
Types Of Increment And Decrement Operators In C
As the name suggests, we have two operators, i.e., increment and decrement operators, which increase and decrease the values of variables/ operands by 1, respectively. These operators have two subtypes each, i.e., one prefix usage and one postfix usage.
In other words, say the base operator is increment, then it has two types- pre-increment (for prefix operation) and post-increment (for postfix operation). The same goes for the decrement operator. So, all in all, we have two postfix operators, i.e., post-increment and post-decrement operators, and two prefix operators, i.e., pre-increment and pre-decrement operators. The pre/postfixes determine if the value addition/ subtraction by a unit will happen after the expression evaluation or before it.
We have listed the four operators in the table below, along with the predefined symbols, names, and a short description.
Operator Symbol |
Name/ Description |
++var |
Prefix increment operator- The increment operator (++) is prefixed before the variable name. |
--var |
Prefix decrement operator- The decrement operator (--) is prefixed before the variable name. |
var++ |
Postfix increment operator- The increment operator is suffixed after the variable name. |
var-- |
Postfix decrement operator- The decrement operator is suffixed after the variable name. |
Here is how these operators affect the value of the variable, depending upon the suffix/ prefix usage-
- The pre-increment and pre-decrement operators (++var and --var) increase or decrease the variable's value before returning the modified value. To put it another way, the adjustment is made before the value of the variable is used in any further computations.
- In contrast, the post-increment and post-decrement operators (var++ and var--) first return the variable current value before increasing or decreasing it. After the value is used in any additional calculations, the update is applied.
Increment Operators In C
Programming languages like C employ increment operators to raise a variable's value by a predetermined percentage. They are frequently employed in calculations, loops, and other scenarios/ complex expressions that require updating a variable value. There are two primary types of increment operators, which are the pre-increment and post-increment operators in C.
Pre-Increment Operator In C (++x)
The prefix increment operator (++variable) is placed before the variable it modifies. When encountered, it increases the value of the variable by 1 and then uses this updated value in the statement or expression evaluation where it appears.
Syntax of the Pre-Increment Operator:
++variable
Here,
- The double plus sign is the increment operator (++), which is being used as a prefix.
- The variable refers to the name of the variable in conditional/ mathematical expression.
Algebraic Example:
Suppose we have a variable x with an initial value of 5. Using the prefix increment operator (++x), the variable is incremented by 1 before being used in an expression x = ++5. The value of x becomes 6 once the pre-increment operator is used. The variable x is then given the incremented value once more.
Code Sample:
Output:
The original value of var: 4
Value of var after prefix increment: 5
Explanation:
We begin the sample C program above by including the <stdio.h> file, which contains the essential input/ output operations.
- Then, we define the main() function, which is the entry point of program execution.
- Inside main(), we declare a variable, var, of data type integer and initialize it with the value 4.
- Next, we use the printf() function to print the initial value of this variable along with a phrase.
- Here, we use a formatted string with the %d format specifier, which acts as the placeholder for the value of var.
- We also use the newline escape sequence (\n) to shift the cursor to the next line.
- After that, we apply the pre-increment operator (i.e., ++var) on the var variable to increase its value by 1. This increases the value from 4 to 5 and updates it to the variable var.
- Once again, we use the printf() function to print the updated value with a formatted string.
- Finally, the program returns 0, signaling successful completion.
Post-Increment Operator (x++)
The post-increment operator is applied or written after the variable in the single/ conditional expression (variable++). In this case, the current value of the variable is initially used in the expression or statement where it appears, and then the variable is incremented by 1.
Syntax of the Post-Increment Operator:
variable++
The syntax is similar to the pre-increment operator syntax, with the only difference being that the operator is used as a suffix here.
Algebraic Example:
Let's consider a variable y with an initial value of 3. Using the post-increment operator (y++), the variable is used in an expression first, and then it is incremented in the expression y = 3++. In this case, the original value of y, which is 3, is used in the expression.
After the single expression is evaluated, the variable y is incremented by 1. The updated value is not assigned back to the variable unless explicitly done so.
Code Sample:
Output:
The original value of var1: 23
Value of var1 after postfix increment: 24
Explanation:
In the post-increment C program example above-
- Inside the main() function, we declare an integer variable called var1 and initialize it with the value 23.
- Using the printf() function with a formatted string, format specifier, and newline, we print the value of this variable.
- Next, we use the post-increment operator on the variable (i.e., var1++) to update its value. This increases the value of var1 to 24, from 23, and updates it in the variable.
- So, after the increment operation is done, we again print the updated value to the window using printf() along with a formatted string.
- The program completes execution successfully, with the return 0 statement.
Decrement Operators In C
In programming languages, including C, we use decrement operators to reduce/ decrease a variable's value by a predetermined percentage (here, 1 unit). These operators are the opposite of the increment operator and offer a practical way to subtract a value from a variable.
The pre-decrement and post-decrement operators are the two primary types of decrement operators.
Pre-Decrement Operator In C (--x)
The pre-decrement operator (--variable) is positioned before the variable it modifies. When encountered, it decreases the value of the variable by 1 and then utilizes this updated value in the expression or statement where it appears.
Pre-Decrement Operator Syntax:
--variable
Here,
- The double minus (--) symbol represents the decrement operator.
- The variable refers to the name of the variable on which the operator is being applied. It is being used as a prefix here.
Algebraic Example:
Consider an example where the starting value of the variable x is 5. Then, the single expression x = --5 means that the value of variable x is lowered by 1 before being utilized in the given expression. So, using the prefix decrement operator (--x), the value of x becomes 4 after using the prefix decrement operator. The variable x is then given the decremented value once more.
Code Snippet:
Output:
The original value of number: 2
Value of number after prefix decrement: 1
Explanation:
- We begin this example by including the essential input/ output header file and start the main() function.
- Then, we declare and initialize an integer variable called number with the value 2.
- Using the printf() function with formatted string, %d format specifier, and newline, we output the value of the number.
- Next, we apply the prefix decrement operator to the variable (i.e., --number), which decreases the value of the number by 1. That is, the value becomes 1 from 2.
- So when we again print the value of the variable, the output is 1.
- Finally, the program terminates with a return 0 statement, indicating successful completion.
Post-Decrement Operator In C (x--)
The postfix/ post-decrement operator is applied after the variable (i.e., variable--). In this case, the current value of the variable is initially used in the expression evaluation or statement where it appears, and after that, the variable is decremented by 1.
Post-Decrement Operator Syntax:
variable--
The syntax for this is similar to that of the pre-decrement operator. The primary difference between prefix and postfix is that here, the operator comes after the variable name.
Algebraic Example:
Consider a variable named y that has an initial value of 7. In this case, the variable is first utilized in an expression, then decremented using the postfix decrement operator (y--). That is, the expression evaluation of y = 7--means we use the original value of y, which is 7. The variable y is reduced by 1 after the expression evaluation is done.
Note that the variable does not receive the new value unless explicitly assigned.
Code Snippet:
Output:
dec_variable = 10
ans = 9
Explanation:
- In this example, we declare an integer variable called dec_variable and initialize it with a value of 10 inside the main() function.
- Next, we print the value to the console using the printf() function, formatted string, format specifier and escape sequence.
- Then, we apply the post-decrement operator to it (i.e., dec_variable--), which decreases the value of the variable from 10 to 9.
- Any operation we perform after applying the decrement operator will use the updated value. So when we once again use the printf() function to print the value, the output is 9.
- The program finally terminates successfully with a return of 0.
Check this out- Boosting Career Opportunities For Engineers Through E-School Competitions
Precedence Of Increment And Decrement Operators In C
Precedence refers to the order in which operators are evaluated in an expression.
Higher precedence means an operator is evaluated before operators with lower precedence. In this section, we will discuss the operator precedence rules in increment and decrement operators in C with examples.
Increment (++) and Decrement (--) Operator In C | Precedence Rules
Both increment and decrement operators have a relatively high precedence. That is, they have a higher precedence than most other unary operators and many binary operators. This means that whenever used together with other operators, the expression evaluation will give preference to the unary increment and decrement operators in C.
Code Example:
In this example, the higher precedence of the increment and decrement operators influences the order of operations. The prefix increment and postfix decrement are applied before the multiplication and subtraction, demonstrating that the unary operators take precedence over the binary operators.
Precedence amongst Postfix and Prefix Operators: The precedence of postfix operators is higher than prefix operators here. That is, when used in prefix notation (i.e., pre-increment and pre-decrement operators), both the increment or decrement operations in expressions have equal precedence within themselves but lower precedence than postfix operations. However, this may be affected by the associativity of the operators in complex expressions.
So, if we have an expression with pre-increment and pre-decrement operators, as well as post-increment and post-decrement operators. Then, the post-increment and post-decrement operators will be evaluated before the pre-increment and pre-decrement operators in C.
Code Example:
In this example, the post-increment and post-decrement operators are evaluated before the pre-increment and pre-decrement operators, confirming the precedence rules in C. Here is the breakdown of the logic behind this code-
- In the evaluation of b, we first use the initial value of a (i.e., 3), and then the post-increment operator increases the value of a to 4 since there is precedence of postfix operators.
- This is taken by the pre-increment operator, which makes the value of a 5. This gives us the result, 3+5, which equals 8.
- In the evaluation of c, the initial value of a is 5, which is then first decremented by the postfix operator, then once again by the prefix operator, making the second value of a in the expression 2.
- The result is then 5-2, which equals 3.
Precedence of Postfix Increment and Decrement Operators in C with other Postfix Operators: When used in postfix notation, i.e., post-increment and post-decrement usage, the increment or decrement operation has the same precedence as other postfix operators, such as array subscripting (arr[i]) and member access (struct.member).
Example:
int a = 5;
int b = 2 * ++a;
In this example, the prefix increment (++a) has higher precedence than the multiplication (*) operation, so a is incremented first in the current operation, and then the multiplication takes place.
Note: Increment and decrement operators are commonly used in loop statements/ constructs, taking advantage of their high precedence to succinctly control loop variables.
Associativity Of Increment And Decrement Operators In C
The associativity of operators determines the direction of expression evaluation. It is crucial to understand this, especially when working with complex expressions. The two directions in which operators in expressions are evaluated are either left-to-right or right-to-left.
For increment and decrement operators in C, the associativity is left to right. That is, when an expression has pre-increment and pre-decrement operators, then the leftmost operator will be evaluated first, and so on, depending upon the placement in code.
Code Example:
Output:
Result: 6
Updated value of x is: 5
Explanation:
In the code provided above,
- We define two variables x (with a value of 5), and y (without any initial value.
- We initialize y, by applying a series of arithmetic, incremenet and decrement operators. Here-
- The pre-increment operator increases the value of x by 1, to 6, before being used in the expression.
- The post-decrement operator then takes this value (i.e.), but it is applied after the expression has been evaluated.
- So the final evaluation of the expression turns, 6 * 2 - 6, which equals 12. After this evaluation the updated value of x will be 5, since the expression returns the result of the rightmost section of the expression.
So, combining the increment and decrement operator precedence rules and associativity, we can say that when an expression has all four operators. The postfix operators will be evaluated before prefix operators. However, given the associativity, the leftmost operator will be given first preference in the current operation evaluation.
Difference Between Increment And Decrement Operator In C
We have discussed the fundamental programming concepts of increment and decrement operations in C individually. In the postfix operators, both increment and decrement are the same in the sense that they update the value after the expression has been evaluated. There are some fundamental differences in behavior of the operators. The same goes for the prefix operators.
In the difference table below, we have listed the most prominent differences between the increment and decrement operators in C.
Feature | Increment Operator (++) | Decrement Operator (--) |
---|---|---|
Syntax | ++variable or variable++ | --variable or variable-- |
Operation | Increases the value of the variable by 1. | Decreases the value of the variable by 1. |
Expression Result |
The prefix usage (++variable) returns the updated value. |
The prefix usage (--variable) returns the updated value. |
The postfix (variable++) returns the original value before the update. |
The postfix (variable--) returns the original value before the update. |
|
Order of Execution | Prefix (++variable): Increments first, then uses the updated value. | Prefix (--variable): Decrements first, then uses the updated value. |
Postfix (variable++): Uses the current value, then increments. | Postfix (variable--): Uses the current value, then decrements. | |
Sequence Point | Prefix (++variable): Creates a sequence point after the update. | Prefix (--variable): Creates a sequence point after the update. |
Postfix (variable++): Creates a sequence point after the use. | Postfix (variable--): Creates a sequence point after the use. | |
Performance Considerations | Prefix forms may be more efficient in certain cases. | Prefix forms may be more efficient in certain cases. |
Undefined Behavior | Modifying the same variable more than once within a sequence point leads to undefined behavior. | Modifying the same variable more than once within a sequence point leads to undefined behavior. |
Combined Example For Increment & Decrement Operators In C
Output:
The value of y after evaluation: 6
Iteration 1: x = 5
Iteration 2: x = 6
Iteration 3: x = 7
The value of z after evaluation: 8
The value of x after evaluation: 3
Explanation:
This C program code example showcases the implementation of increment and decrement operators in C.
- We begin by declaring two integer variables, x and y. We initialize variable x with the value 5 inside the main() function.
- Next, we initialize the value of variable y with an expression that applies pre-increment, post-decrement, and arithmetic operations, as mentioned in the code comments. Here-
- The prefix increment operator is applied first since the associativity is from left to right. This increases the value of x from 5 to 6, and the expression becomes (6 * 2 - x--).
- Then, the postfix decrement operator is applied since it has higher precedence than arithmetic operations. However, since it is a postfix operator, the value deduction will happen after the expression evaluation is complete. So, the value of x remains 6.
- The expression thus becomes (6*2-6). Here, the multiplication operator will be applied first, resulting in (12-6), with the final output being y=6.
- We use the printf() function with a formatted string to output the value of y to the console.
- After the expression 1 is evaluated, the value of x is once again set to 5 with the application of the post-decrement operator automatically.
- Next, we initiate a for loop to show the implementation of the postfix increment operator. Here-
- The loop begins with the initial value of variable x and prints the value to the console using the printf() function.
- There are three iterations, with the value of x being incremented by 1 after every iteration.
- This shows how the increment operator is used in loop counters/ structures.
- After the loop completes execution, the value of x stands at 7. We reset this value back to 5, as mentioned in the code comment.
- Next, we define a third variable, z, and initialize it with an expression that applies the decrement operators to x. Here-
- The prefix decrement operator is applied to x (i.e., --x), which reduces the value to 4. The expression thus becomes (4 + x--).
- After that, the addition operator is skipped since the decrement operator has higher precedence. The post-decrement operator is evaluated, but it will reduce the value after the expression.
- So, the expression remains (4+4), and the value of z becomes 8.
- We use the printf() function to display the value of z and the value of x after the evaluation.
- The program concludes by returning 0 from the main function.
Note- Using too many increment and decrement operators in may lead to undefined behavior in some compilers. Also some compilers might give preference to the rules of associativity over the rules of precedence, and vice versa. This might lead to a difference in the result of an expression evaluation.
Complexity Analysis:
The complexity of the examples is constant (O(1)) since the operations involve a fixed number of increments and decrements. The loop in Example 2 runs a fixed number of times, contributing to the overall constant complexity. The performance impact is negligible for small constant values of increments and decrements.
Some Interesting Facts About Increment And Decrement Operators In C
- Precedence and Associativity: The increment and decrement operators have higher precedence than most other operators in C. For example, the expression ++x * 2 is equivalent to (++x) * 2.
- Overuse and Readability: The increment and decrement operators can be convenient for concise code. However, excessive use of these operators, especially in complex expressions, can reduce code readability and make it harder to understand the intended logic. It is important to strike a balance between brevity and clarity when using these operators.
- Usefulness in Loop Constructs: Increment and decrement operators are often employed in loop constructs, where they contribute to concise and readable code. For example, the common idiom for traversing an array involves using the increment operator:
for (int i = 0; i < size; ++i) {
// Loop body
}
- Performance Considerations: In some cases, using the prefix form of the increment/decrement operator can be more efficient than the postfix form. This is because the postfix operator may involve creating a temporary variable to store the original value.
- Counter variables: Counter variables are variables commonly used to keep track of the number of iterations or occurrences of certain events within a program. Increment and decrement operators are particularly useful when working with counter variables.
- Wrapping Behavior: Incrementing or decrementing beyond the limits of the data type can lead to unexpected results due to wrapping. For example, incrementing the maximum value of an unsigned int will wrap around to zero.
Conclusion
Understanding and mastering the increment and decrement operators in C is essential for writing efficient and concise code. These operators offer a convenient way to manipulate variables and control programming scenarios, contributing to both readability and performance optimization. By grasping the nuances of prefix and postfix operations, developers can wield these types of operators effectively, unlocking the full potential of the C programming language. As you delve deeper into the world of C programming, remember that the judicious use of increment and decrement operators can significantly enhance your code's clarity and efficiency.
Also read- 100+ Top C Interview Questions With Answers (2023)
Frequently Asked Questions
Q. What is the ++ operator in C?
The double plus (++) operator in C represents the increment operator that is used to increase a single operand value by 1. When used as a prefix (++variable), the variable is incremented first, and the updated value is used in the expression. In the postfix form (variable++), the current value of the variable is used in the expression, and then the variable is incremented. It is commonly employed in loops for iterative operations. The increment operator is specific to variables and numeric types, and it enhances code readability by providing a concise way to express incrementing operations in C programs.
Q. What is the decrement operator?
The decrement operator in C is represented by a double minus sign (--), and it is used to decrease the value of a variable by 1. Similar to the increment operator (++), the decrement operator has two forms, i.e., pre-decrement and post-decrement.
Pre-decrement (--variable): The value of the variable is decreased by 1 before its use in the expression.
Code Snippet:
int x = 5;
int y = --x; // y is assigned the value of x after it is decremented
// Now, x is 4, y is 4
Post-decrement (variable--): The value of the variable is used in the expression, and then it is decremented by 1.
Code Snippet:
int a = 10;
int b = a--; // b is assigned the current value of a before it is decremented
// Now, a is 9, b is 10
Like the increment operator, the decrement operator is frequently used in loops for iterative purposes. It is applicable to variables of numeric types, such as integers, floating-point numbers, etc. It enhances code conciseness and readability by providing a shorthand for decrementing operations in C programs.
Q. What is getch () in C?
In C programming situations, the getch() is a function that is commonly used to read a single character from the keyboard. It is part of the standard C library and is typically found in the <conio.h> header file. However, note that the use of the <conio.h> library and some of its functions, including getch(), are not standardized and are considered non-portable. It means that these functions may not be available or behave differently on all C compilers.
Q. What is the difference between A ++ and ++ A in C?
In C and many other complex programming languages, ++ is the increment operator, and it is used to increase the value of a variable by 1. The placement of the increment operator (++) in relation to the variable determines whether the increment operation is performed before or after the current value of the variable is used.
A++ (Post-increment): This is known as post-increment. When used in this form, the current value of the variable is used in the arithmetic expression, and then the variable is incremented by 1.
Code Snippet:
int A = 5;
int result = A++;
// result is assigned the value of A before the increment
// A is now 6
++A (Pre-increment): This is known as pre-increment. When used in this form, the variable is incremented by 1 first, and then the updated value is used in the expression.
Code Snippet:
int A = 5;
int result = ++A;
// A is incremented before its value is assigned to the result
// result is now 6, A is also 6
In summary, the key difference is the order of current operations. That is, A++ uses the current value of A in the expression and then increments it, while ++A increments A first and then uses the updated value in the expression.
This compiles our discussion on increment and decrement operators in C. Here are a few other interesting topics that make a fun read:
- Identifiers In C | Rules For Definition, Types, And More!
- Types Of Errors In C & Handling Demystified (With Examples)
- Compilation In C | A Step-By-Step Explanation & More (+Examples)
- Tokens In C | A Complete Guide To 7 Token Types (With Examples)
- Difference Between C And C++ Explained With Code Example