Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

c - 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?

question from:https://stackoverflow.com/questions/65928711/how-does-casting-a-type-in-a-function-call-work

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...