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
A Puzzle on C/C++ R-Value Expressions?
Here we will see one puzzle about R-value expressions in C. Suppose there is a program which is given below, we have to tell what will be the output and why?
Syntax
~expression; // R-value: computes but doesn't store variable = ~expression; // L-value: stores the result
Example 1: R-value Expression
In this example, the complement operation is performed but not assigned to any variable −
#include <stdio.h>
int main() {
int x = 0xab;
~x; /* R-value: computed but not stored */
printf("%x", x);
return 0;
}
ab
So, there is no change. But why? The reason is ~x is converting x into its complemented form, but that value is not assigned to any variable. The expression is an R-value expression. Until an L-value assignment is used, the computed result will not be stored into the variable.
Example 2: L-value Assignment
If we assign the complement result back to the variable using L-value assignment, it will look like this −
#include <stdio.h>
int main() {
int x = 0xab;
x = ~x; /* L-value: result is stored back to x */
printf("%x", x);
return 0;
}
ffffff54
Key Points
- R-value expressions compute a value but don't modify any variable unless assigned.
- L-value assignments store the computed result into a variable.
- The bitwise NOT operator
~flips all bits of the integer. - In a 32-bit system,
~0xabbecomes0xffffff54.
Conclusion
This puzzle demonstrates the difference between R-value expressions and L-value assignments in C. An expression like ~x computes the result but doesn't store it unless explicitly assigned to a variable.
