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

1

I created a function that returned a certain value, when I use this function in the main function of the program, how can I do to store the return of it, and for example, display that return in 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;
}
    
asked by anonymous 15.05.2017 / 21:41

1 answer

2

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

I took advantage of 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);
}

See running on ideone . And on the Coding Ground (you're in trouble, post it). Also put it on GitHub for future reference .

The variable distancia is not even there, in fact all of them, but to do it in the same way and indicate how to do it if it were something that the variable is needed. 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 do the simple straightforward calculation without creating a function, but I understand it to be a learning issue. You just can not learn to do it like this if you do not have to.

A good looking question .

    
15.05.2017 / 22:11