Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When all does comma operator not act as a comma operator?

If you see this code,

class A{
public:
    A(int a):var(a){}
    int var;
};

int f(A obj) {
    return obj.var;
}

int main() {
    //std::cout<<f(23);    // output: 23
    std::cout<<f(23, 23);  // error: too many arguments to function 'int f(A)'
    return 0;
}

f(23, 23) does not compile because the comma acts as a separator here and not as a comma operator.

Where all does a comma not work as a comma operator? Or the other way around?

like image 509
Lazer Avatar asked Jun 27 '10 18:06

Lazer


1 Answers

From a grammatical point of view, the parameters of a function call form an optional expression-list inside parentheses. An expression-list consists of one or more assignment-expression separated by a comma token. A comma can only signify a comma operator where an expression is expected.

The comma operator makes an expression out of an expression, a , and an assignment-expression, but an expression involving a comma operator is not itself an assignment-expression so can't appear in an expression-list except where it's a constituent of something that is an assignment-expression.

For example, you can surround any expression (including one using the comma operator) inside parentheses to from a primary-expression which is an assignment-expression and hence valid in an expression-list.

E.g.

postfix-expression where the expression-list consists of two assignment-expression each of which is an identifier.

f( a, b );

postfix-expression where the expression-list consists of a single assignment-expression which is a primary-expression which is a parenthesized expression using the comma operator.

f( (a, b) );
like image 53
CB Bailey Avatar answered Sep 28 '22 12:09

CB Bailey