I have a doubt regarding the casting of types in C. Is it safe to pass literals to function parameters(expecting different types but compatible types) without explicitly casting? For example here is an example code:
#include<stdio.h>
int sum(int a, int b){
return a b ;
}
int main(void){
int x = sum(6U,5U) ; /* Does the compiler automatically casts unsigned to int?
or do I need to explicitly cast it sum( (int) 6U, (int) 5U) ?*/
printf("%d \n", x);
return 0;
}
The code runs fine but I wanted to know if this legal or can lead to undefined behaviours (assuming no overflows) ?
CodePudding user response:
If an argument in a function call corresponds to a parameter with a declared type, the argument is converted to the parameter type, per C 2018 6.5.2.2 7.
If the argument does not correspond to a parameter with a declared type, the default argument promotions are performed. This occurs when the argument corresponds to the ...
part of a function prototype, per C 2018 6.5.2.2 7, or when called function does not have a prototype, per 6.5.2.2 6.
The default argument promotions consist of the integer promotions (which largely promote integer types narrower than [technically of lower rank] int
to int
) and promote float
to double
.
Note that the applicable function type for these conversions is the type of the expression used to call the function. A function may be defined in one place with a prototype, such as int foo(char *a) { ... }
, but declared in another place without a prototype, such as int foo();
. The declaration visible at the function call is what determines which conversions will be performed. This is particularly so when a function is called via a pointer.
Note that these conversions are not casts. A cast is a specific operator in source code, a type name in parentheses, for which a conversion is performed. The cast, such as (int)
in source code, is different from the operation, the same way a
in source code is different from the addition performed for it.