0d: 00h: 00m: 00s

šŸŽ Get 3 extra months of learning — completely FREE

That's 90 extra days to master new skills, build more projects, and land your dream job.

Become a PRO
Background Image

šŸŽ Get 3 extra months of learning completely FREE

Become a PRO
Varun Malik
PRO
last week
Varuncountry asked

Why does my C function return an integer even when I pass floats, and should I change the return type to double?

Abhay Jajodia
Expert
last week
Abhay Jajodia answered

Hello Varun, really nice question.

A lot of beginners run into this when they start working with functions in C, so you’re definitely on the right track noticing it.

Here’s the simple idea:
If you write a function like this:

int getProduct(float a, float b)

C expects that function to return an int, no matter what you actually calculate inside it. So even if a * b produces a floating-point value, C will convert it to an integer when returning it. That’s why the decimal part disappears.

If you want the full, precise result, you need the function to return a floating-point type:

double getProduct(double a, double b) {
    return a * b;
}

This keeps the decimal values and avoids losing accuracy.

And one more thing students often miss:
You have to actually use the returned value, otherwise it's wasted:

double result = getProduct(3.5, 4.6);
printf("Product: %.2f\n", result);

If anything about return types still feels unclear, feel free to ask — I’m happy to help you understand it fully.

C
This question was asked as part of the Learn C Programming course.