A Puzzle on C/C++ R-Value Expressions?


Here we will see one puzzle. Suppose there is a program which is given as below, we have to tell what will be the output and why?

Example

#include<iostream>
using namespace std;
int main() {
   int x = 0xab;
   ~x;
   cout << hex << x;
}

So what will be the output? The ~x is doing the complement operation. So is it show the complemented result in hex form?

Well the output is like the following

Output

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 R-value expression. Until the Lvalue is used it will not be stored into some variables. If we put L-value it will be look like this −

Example

#include<iostream>
using namespace std;
int main() {
   int x = 0xab;
   x = ~x;
   cout << hex << x;
}

Output

ffffff54

Updated on: 31-Jul-2019

79 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements