Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my program evaluating arguments right-to-left?

I am learning C so I tried the below code and am getting an output of 7,6 instead of 6,7. Why?

#include <stdio.h>
int f1(int);
void main()
{
    int b = 5;
    printf("%d,%d", f1(b), f1(b));
}
int f1(int b)
{
    static int n = 5;
    n++;
    return n;
}
like image 693
Sanket Wankhede Avatar asked Jun 12 '19 09:06

Sanket Wankhede


People also ask

Does order of arguments matter for a function?

Yes, it matters. The arguments must be given in the order the function expects them.

What is the correct way to enter an argument in a function?

We can pass an argument to a function while calling the function by simply giving the value as an argument inside the parenthesis.

What is the purpose of evaluating an argument?

Decide if the argument is deductive or non-deductive. Determine whether the argument succeeds logically. If the argument succeeds logically, assess whether the premises are true.

What is evaluation order of function parameters in C?

evaluation order and sequence pointsOrder of evaluation of the operands of any C operator, including the order of evaluation of function arguments in a function-call expression, and the order of evaluation of the subexpressions within any expression is unspecified (except where noted below).


1 Answers

The order of the evaluation of the function arguments is unspecified in C. (Note there's no undefined behaviour here; the arguments are not allowed to be evaluated concurrently for example.)

Typically the evaluation of the arguments is either from right to left, or from left to right.

As a rule of thumb don't call the same function twice in a function parameter list if that function has side-effects (as it does in your case), or if you pass the same parameter twice which allows something in the calling site to be modified (e.g. passing a pointer).

like image 108
Bathsheba Avatar answered Oct 20 '22 23:10

Bathsheba