[Solved] My program returns 4 instead of expected value 40 [closed]


You have 2 ways of having a function change data outside it: you can pass a variable by reference and update it, or you can return a value and use that. You are mixing half of each method instead. I reordered the code to make my commentary clearer.

#include <stdio.h>

int value(int *a);

// here you are passing by reference, good
int value(int *a){
    int c = (*a)*10; // but you don't change a
    return c;  // instead you return a new value
}

int main(){
    int num = 4;
    value(&num); // but here you ignore the new value. 
    printf("value of number is = %d", num);
    return 0;
}

to make reference way work, you need:

#include <stdio.h>
    
void value(int *a);
    
int main(){
    int num = 4;
    value(&num);
    printf("value of number is = %d", num);
    return 0;
}

void value(int *a){
    *a = (*a)*10; // change the value that a points at
    // no need to return anything
}

or to make the return way work:

#include <stdio.h>
// no need to pass by reference
int value(int a);
    
int main(){
    int num = 4;
    num = value(num); // use value return by function
    printf("value of number is = %d", num);
    return 0;
}

int value(int a){
    int c = a * 10;
    return c;
}

6

solved My program returns 4 instead of expected value 40 [closed]