0

I am writing this code that calculates Miles per Gallon where the number of miles and gallons are read from the keyboard. The program will perform a simple calculation to get the miles per gallon. I wrote a function in order to do this this calculation but it is not returning the result. Inside the function everything is working as it should. I even wrote a printf to ensure the calculation was done correctly. But then when I try to return it to the main function, the member of the structure appears to have a value of 0 instead of the result of the calculation. Here is my code:

#include <stdio.h>
#include <stdlib.h>

struct gas {
 float distance;
 float gals;
 float mpg;
};

float CalculateMpg(struct gas idk){
    idk.mpg = idk.distance / idk.gals;
    printf("%f \n", idk.mpg);
    return idk.mpg;
}

int main()
{
    struct gas idk;

    printf("Enter distance (in miles): ");
    scanf("%f", &idk.distance);
    printf("Enter gallons fueled: ");
    scanf("%f", &idk.gals);

    CalculateMpg(idk);
    printf("%f \n", idk.mpg);
    printf("Miles driven gallons used with %.2f miles and %.2f gallons: %.2f mpg \n", idk.distance, idk.gals, idk.mpg);

    return 0;
}
Rivf
  • 123
  • 8
  • 1
    C passes by value. I would recommend reading a good book or tutorial if you didn't learn that yet. The 10 new questions about it every day aren't useful. Passing by value means you modify a **copy** of `idk`'s `mpg`, not the member in the one declared in `main()`. But you **return** it, so why not just read that result instead of ignoring it? However, then you don't need to assign to the copy at all, or store `mpg` per-instance, if it can always be calculated on-demand... but if you must, the 2nd option is modify in-place, ie pass via pointer, in which case there's not any point returning too. – underscore_d Nov 09 '20 at 14:48
  • 1
    Does this answer your question? [Passing by reference in C](https://stackoverflow.com/questions/2229498/passing-by-reference-in-c) – underscore_d Nov 09 '20 at 14:51

1 Answers1

1

Reason: Because C uses call-by-value

When you call function CalculateMpg(), idk is copied to argument variable by value.

In this function, only copied argument is edited.

You should make function uses pointer and call it to CalculateMpg(&idk)

Sample Solution:

#include <stdio.h>
#include <stdlib.h>

struct gas {
 float distance;
 float gals;
 float mpg;
};

float CalculateMpg(struct gas* idk){
    idk->mpg = idk->distance / idk->gals; // arrow is just syntactic sugar of (*idk).field
    printf("%f \n", idk->mpg);
    return idk->mpg;
}

int main()
{
    struct gas idk;

    printf("Enter distance (in miles): ");
    scanf("%f", &idk.distance);
    printf("Enter gallons fueled: ");
    scanf("%f", &idk.gals);

    CalculateMpg(&idk);
    printf("%f \n", idk.mpg);
    printf("Miles driven gallons used with %.2f miles and %.2f gallons: %.2f mpg \n", idk.distance, idk.gals, idk.mpg);

    return 0;
}
Jiho Lee
  • 957
  • 1
  • 9
  • 24