user16045271
user16045271

Reputation:

How to send back the values inside a void function to main function in C?

How can I send back the value inside a void function to the main function if the condition restricts me from using the non-void function to return those values?

here's my example code:

void calcTotalPaid(float total){
    float totalPaid=0;
    totalPaid += total;
}

Upvotes: 0

Views: 2519

Answers (3)

Sumit Baloda
Sumit Baloda

Reputation: 23

Here is the explanation:

If you use a void function then it never returns a value into a called function which is here int main(). It shows an error.

You are passing the argument value into the parameter (a local variable that is declared when declaring the function prototype), so what if you pass the address of that argument into the calling function? Yes, using a pointer variable, you should pass the argument memory location.

In the called function, you have the memory address of that particular argument. Whenever the new values are inserted into that argument (which is now a local variable), it saves on that memory location because we have here that address of memory location.

Here is your program:

#include<stdio.h>//preprocessor directive for function printf()
void calTotalPaid (float *pointer, float total)//function declartion and
//definition of function
{
    float totalpaid = 0;
    totalpaid = totalpaid + total;
    *pointer = totalpaid;
}

int main ()
{
    float value, total = 0;
    calTotalPaid (&value, total);//calling the function and passing the memory 
    //location to the function parameter so if function changed the value stored 
    //at value's memory location it will change in entire program.
    printf ("The value is %f\n", value);
    return 0;
}

Upvotes: 2

user15375057
user15375057

Reputation:

use call by reference technique. Pass address of a variable from main to calcTotalPaid(), and store the address in a pointer variable.

void  calcTotalPaid(float * total_paid , float total){
 *total_paid = 0 + total;
}

Upvotes: 0

MikeCAT
MikeCAT

Reputation: 75062

You should pass a pointer to a variable that will receive the result and use that.

#include <stdio.h>

void calcTotalPaid(float* res, float total){
    float totalPaid=0;
    totalPaid = totalPaid + total;
    *res = totalPaid;
}

int main(void) {
    float value = 0;
    calcTotalPaid(&value, 3.14);
    printf("%f\n", value);
    return 0;
}

Upvotes: 2

Related Questions