Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to do something like foo(x, &x)?

Note, I would not write code like this. I'm just curious, and it would help me writing a better answer for another question. But let's say that we have this function:

void foo(int a, int *b)
{
    *b  = 2*a;
}

And call it like this:

int x=42;
foo(x, &x);

Apart from the fact that it is a very strong code smell, can this cause any real problems? Is it UB or does it violate any rules in the C standard?

like image 441
klutt Avatar asked Jan 25 '23 18:01

klutt


1 Answers

This

int x=42;
foo(x, &x);

is a well-formed code. The order of the evaluation of arguments is not important in this case.

In fact the function call is equivalent to

foo( 42, &x);

because the first argument is passed by value.

like image 135
Vlad from Moscow Avatar answered Jan 30 '23 00:01

Vlad from Moscow