Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic conversions and promotions in function calls in C++

How to learn which are conversions and promotions in function calls?.

From my previous question related to why are some functions called despite of others could have also been called too, i want to underline three keywords: conversions, promotions, perfect matches.

  • perfect matches is the simplest:

    • int fun(int a) called with a variable declared int x;
    • int fun(float a, double b) called with a variable declared float x; double y;
    • int fun(char a, string s) called with a variable declared char x; string y
    • ...etc
  • for conversions and promotions i'm only going to mention that:

Numeric conversions: Unlike the promotions, numeric conversions may change the values, with potential loss of precision.

Numeric promotions: a conversion from a smaller type to a larger same type (E.g char to int), but without any loss of content

Here comes the part that is not that simple. I would like someone to explain the way you need to think when you analize the function parameters for different situations as calling:

  • int fun(double a) with float x vs int fun (float a) called with double x

I would like to actual see some examples, because for a begginer is not easy to understand the references from cpp.

like image 518
Cătălina Sîrbu Avatar asked Jan 26 '26 19:01

Cătălina Sîrbu


1 Answers

Having:

int fun(double a)

Calling with float x makes this a floating-point promotion, this is because a double will always be the same or a bigger size than a float which means that our parameter a will always be able to hold the data we pass to it through our float, there is no loss of data that can occur and thus it is a promotion.


However, having:

int fun(float a)

Calling with double x makes this a floating-point conversion where loss of data or possible UB can occur. Exactly because this scenario is the opposite of the one above, our double might hold a value not representable in a float which in turn might lead to UB. See Floating-point conversions for the exact rules on that.

like image 87
Hatted Rooster Avatar answered Jan 29 '26 08:01

Hatted Rooster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!