Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is evaluation order of function parameters in C?
In C programming, when we pass arguments to a function, a common question arises: what is the order of evaluation of function parameters? Is it left to right, or right to left? The C standard does not specify the evaluation order, making it implementation-defined behavior.
Syntax
function_name(arg1, arg2, arg3, ...);
Example: Testing Parameter Evaluation Order
Let's examine a program that demonstrates the evaluation order by using side effects −
#include <stdio.h>
void test_function(int x, int y, int z) {
printf("The value of x: %d
", x);
printf("The value of y: %d
", y);
printf("The value of z: %d
", z);
}
int main() {
int a = 10;
test_function(a++, a++, a++);
return 0;
}
The value of x: 12 The value of y: 11 The value of z: 10
How It Works
From the output, we can observe that the parameters were evaluated from right to left:
- First, the rightmost parameter
zgets the value 10 (a++ returns 10, then a becomes 11) - Then, parameter
ygets the value 11 (a++ returns 11, then a becomes 12) - Finally, parameter
xgets the value 12 (a++ returns 12, then a becomes 13)
Key Points
- Parameter evaluation order is implementation-defined in C − different compilers may behave differently
- Common implementations evaluate parameters from right to left, but this is not guaranteed
- Writing code that depends on evaluation order leads to undefined behavior and should be avoided
- For portable code, avoid side effects in function arguments
Conclusion
While many C implementations evaluate function parameters from right to left, this behavior is not standardized. It's best practice to avoid relying on parameter evaluation order and write code that doesn't depend on such implementation details.
Advertisements
