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
Can we use function on left side of an expression in C and C++?
In C and C++, you normally cannot use a function call on the left side of an assignment if it returns a value by copy, because function calls return non-assignable temporary values. However, there are specific cases where this is possible −
Syntax
// Invalid - function returns value by copy function_name() = value; // Compiler error // Valid - function returns pointer (C) *function_name() = value; // Dereference pointer // Valid - function returns reference (C++ only) function_name() = value; // Direct assignment to reference
Understanding lvalues and rvalues
To use something on the left side of an assignment, it must be an lvalue − a modifiable memory location. Function calls that return values by copy are rvalues (temporary values) and cannot be assigned to.
Example 1: Valid Case in C - Using Pointer Dereference
This example shows how to use a function on the left side by returning a pointer and dereferencing it −
#include <stdio.h>
// Function returns a pointer to a static variable
int* getPtr() {
static int x = 5;
return &x;
}
int main() {
printf("Before: %d\n", *getPtr());
// Valid: Assigning through pointer dereference
*getPtr() = 100;
printf("After: %d\n", *getPtr());
return 0;
}
Before: 5 After: 100
Example 2: Invalid Case - Function Returns Value by Copy
This example demonstrates what happens when you try to assign to a function that returns a value −
#include <stdio.h>
// Function returns a value (not a pointer)
int getValue() {
return 5;
}
int main() {
// This will cause a compiler error
// getValue() = 10; // Uncomment to see error
printf("Function returned: %d\n", getValue());
printf("Cannot assign to function return value\n");
return 0;
}
Function returned: 5 Cannot assign to function return value
Key Points
- Functions returning values by copy cannot be used on the left side of assignment
- Functions returning pointers can be dereferenced and assigned to:
*function() = value - In C++, functions returning references can be directly assigned to:
function() = value - Always ensure returned pointers/references point to valid memory (use static variables, not local ones)
Conclusion
Functions can only be used on the left side of expressions in C when they return pointers that can be dereferenced. This technique is useful for creating modifiable access to static or global variables through function interfaces.
