David542
David542

Reputation: 110163

How does casting a type in a function call work?

Let's say I have something like the following to call a function in C:

void test1(void) {
    int a=7;
    function((short) a);
}

Does the compiler treat this (almost) the same as if it were to create a temporary variable and pass that to the function, for example:

void test1(void) {
    int a=7;
    short tmp_a=(short) a;
    function(tmp_a);
}

Or does the cast do anything differently than the above, at least on a conceptual level?

Upvotes: 0

Views: 742

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222724

Casts are just operators, like multiplication or shifts. When a function argument is an expression, it is evaluated like any other expression. So function((short) a); is equivalent to:

short tmp_a = (short) a;
function(tmp_a);

in the same way that function(a*a); is equivalent to:

int tmp_a = a*a;
function(tmp_a);

Note there are also implicit conversions involved in function calls. If the function has a prototype, arguments are converted to the declared types of the parameters. If there is no prototype, or an argument corresponds to the ... part of a prototype, some default argument promotions are performed.

Upvotes: 4

Related Questions