Skip to content
Related Articles

Related Articles

Result of comma operator as l-value in C and C++

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 29 Sep, 2022
Improve Article
Save Article

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

 Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!