0
#include<iostream>
using namespace std;

class base
{
private:
    int id = 6;
public:
    friend void display();
};

void display()
{
    base b;
    cout<<"Display id" <<b.id<<endl;
    cout<<"Display id", b.id;
}

int main()
{
    display();  
}

Output:

Display id6
Display id

Can someone explain that why cout<<"Display id", b.id; is not throwing error? and if comma (,) is acceptable then what will be the behavior of variables written after comma (,).

Thanks in advance.

van neilsen
  • 547
  • 8
  • 21

1 Answers1

4

C++ has a comma operator, E1, E2 is a perfectly legal expression if E1 and E2 are also expressions. It has very low precedence (lower than <<) so your example brackets like this

(cout<<"Display id"), b.id;

The effect of the comma operator is to evaluate what is on the left-hand side first, and then evaluate what is on the right-hand side. The value returned by the whole expression is the value of the right-hand side.

So in terms of your example

cout<<"Display id", b.id;

is exactly the same as

cout<<"Display id";

It's very rarely used (and doesn't even exist in other languages like Java) so most newbies have never seen it before. But sometimes you see code like this

int ch;
if (ch = in.get(), ch != '\n')

which reads a char into ch and then checks if it is a newline.

john
  • 85,011
  • 4
  • 57
  • 81