Using the result of the comma operator as l-value is not valid in C. But in C++, the result of the comma operator can be used as l-value if the right operand of the comma operator is l-value. For example, if we compile the following program as a C++ program, then it works and prints b = 30. And if we compile the same program as a C program, then it gives a warning/error in the compilation (Warning in Dev C++ and error in Code Blocks).
C
#include<stdio.h> int main()
{ int a = 10, b = 20;
(a, b) = 30; // Since b is l-value, this statement is valid in C++, but not in C.
printf ( "b = %d" , b);
return 0;
} |
OUTPUT: error: lvalue required as left operand of assignment
C++
#include <iostream> using namespace std;
int main()
{ int a = 10, b = 20;
(a, b) = 30;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
return 0;
} |
Output
a = 10 b = 30