How does the compiler know that the comma in a function call is not a comma operator?

后端 未结 6 767
Happy的楠姐
Happy的楠姐 2020-12-06 04:11

Consider the function call (calling int sum(int, int))

printf(\"%d\", sum(a,b));

How does the compiler decide that the

6条回答
  •  一生所求
    2020-12-06 04:43

    The reason is the C Grammar. While everyone else seems to like to cite the example, the real deal is the phrase structure grammar for function calls in the Standard (C99). Yes, a function call consists of the () operator applied to a postfix expression (like for example an identifier):

     6.5.2 postfix-expression:
           ...
           postfix-expression ( argument-expression-list_opt )
    

    together with

    argument-expression-list:
           assignment-expression
           argument-expression-list , assignment-expression    <-- arglist comma
    
    expression:
           assignment-expression
           expression , assignment-expression                  <-- comma operator
    

    The comma operator can only occur in an expression, i.e. further down the in the grammar. So the compiler treats a comma in a function argument list as the one separating assignment-expressions, not as one separating expressions.

提交回复
热议问题