How to store the return value of a function in a local variable in C?

Asked

Viewed 1,466 times

2

I created a function that returned a certain value when using this function in the function main of the program, how can I store its return, and for example, display this return in a printf in main?

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

int distanciaCorrida(int inicio, int fim){
    int distancia = 0;
    distancia = fim - inicio;
    return distancia;
}

int main(){
    int kminicial, kmfinal;
    kminicial = 200000;
    kmfinal = 207349;
    distanciaCorrida(kminicial,kmfinal);
    printf("A distancia percorrida pelo carro foi de %d km",);
    return 0;
}
  • It’s not so much a question of not being able to do it as how to do it. but I’ll put the code

  • Only make int dp = distance Raced(kminitial,kmfinal); and then printf("The distance travelled by the car was %d km", &dp);

  • @Joetorres: The address operator & is too much in your expression; will print the wrong value this way.

  • You’re right. & only goes in scanf not print....

1 answer

2


Just as you can assign a value literal in variable, may assign a expression since you made a subtraction, which is an expression. An expression can contain a number of things that generate some result. A function generates a result, so just use it to assign the variable. See explanations of the terms.

I took advantage and simplified the code.

#include <stdio.h>

int distanciaCorrida(int inicio, int fim) {
    return fim - inicio;
}

int main() {
    int kminicial = 200000;
    int kmfinal = 207349;
    int distancia = distanciaCorrida(kminicial, kmfinal);
    printf("A distancia percorrida pelo carro foi de %d km", distancia);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

The variable distancia there is not even necessary, actually all of them, but to do in the exposed way and indicate how to do if it is something that the variable is necessary. Could do:

printf("A distancia percorrida pelo carro foi de %d km", distanciaCorrida(kminicial, kmfinal));

Except in a case of wanting to generate an abstraction, it is even simpler to make the simple calculation direct without creating a function, but I understand that it is a matter of learning. Just don’t learn to do it all the time if you don’t have to.

One very similar question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.