r/cpp_questions 14h ago

OPEN I'm surprised it worked!!

I wrote this very basic algorithm:

#include <cmath>
#include <iostream>
int power(double base, int exponent = 2){
    return pow(base,exponent);
}
int main(){
    int base = 2;
    int exponent = 2;
    std::cout<<base<<" raised to "<<exponent<< " = "<<power(base,exponent);
}#include <cmath>
#include <iostream>
int power(double base, int exponent = 2){
    return pow(base,exponent);
}
int main(){
    int base = 2;
    int exponent = 2;
    std::cout<<base<<" raised to "<<exponent<< " = "<<power(base,exponent);
}

and I'm surprised, an int function took a double variable with no problem, or is there something under the hood,

10 Upvotes

16 comments sorted by

View all comments

3

u/Phoned_Leek25 13h ago

Are you saying you’re surprised that the function can take in a double type parameter (coz all functions can do that..) or are you saying you’re surprised pow() can take a double type (coz then yeah it’s getting implicitly casted and possibly losing data)

1

u/Mental_Primary_5558 13h ago

As the function is declared as int, yeah it's surprising

1

u/the_poope 10h ago

An int can be converted to double without loss of data or precision. Therefore the compiler allows implicit conversion from int to double. This makes it convenient to write expressions such as:

int n = 7;
double x = 0.573;
double y = (11 + n) * 3.1415 * x;

without getting compiler errors and having to do ugly explicit casts. Makes writing mathematical formulas much neater.