Solving a C Local Variable Issue

  • Thread starter Thread starter Nothing000
  • Start date Start date
AI Thread Summary
To pass a local variable's value from one function to another in C, the function must be declared to return a value, and that value must be captured in the calling function. In the provided code, the function `f1` should return an integer, which can then be assigned to a variable in `main`. The corrected code includes changing the function signature of `f1` to return an `int` and using `scanf` correctly by passing the address of the variable. Additionally, when calling `f2`, it should accept an integer parameter to receive the value returned from `f1`. In C++, the approach is similar, where the return value from `f1` is assigned to a variable in `main`, and then passed to `f2`. Properly managing function return types and parameters is essential for successfully transferring data between functions.
Nothing000
Messages
403
Reaction score
0
Will someone please help me. I can not fiugure out how to get a local variables value to go from one function to another. Here is the source code:

#include <stdio.h>

int f1(int b);


int main()
{
int a = 0;
int b = 0;

f1();
printf("The value returned TO main() FROM f1() is:\n", a);



return 0;
}

int f1()
{
int a = 0;

printf("Enter a whole number.\n");
scanf("%d", a);

return a;
}
 
Computer science news on Phys.org
How do I return the value a back to the main function.
 
What problem are you having? Does the above not work?
 
The second function asks for input by the user and stores that as the variable a. But how do I get the value of a back to the main function.
 
The big question I have is this: How would I get the variable a to go to the function f2 in this
#include <stdio.h>

int f1(int );
int f2(int );

int main()
{
int a = 0;
int b = 0;

f1();
printf("The value returned TO main() FROM f1() is:\n", a);
f2();
return 0;
}int f1()
{
int a = 0;

printf("Enter a whole number.\n");
scanf("%d", a);

return a;
}


int f2()
{
printf("The value you entered for a is:%d\n", a);
}
 
Can anyone help me?
 
Declare your function as returning int, float, etc. Then assign it to a variable of that type. For f2, declare it as taking a parameter of appropriate type, and then pass the argument to it. In C++

Code:
#include <iostream>

int f1();
void f2( int arg);

int main()
{
    int a = f1();
    f2(a);
    return 0;
}

int f1()
{
    return 42;
}

void f2( int arg)
{
    std::cout << "f1 returned " << a << std::endl;
    return;
}

Good luck,
Tim
 
Oh, I see the problem, when you call the function f1, you need to put the returned value somewhere when it comes back.

int x = f1();
printf("The value returned TO main() FROM f1() is:\n", x);

I see nmtim has already addressed that.
 

Similar threads

Replies
12
Views
2K
Replies
12
Views
2K
Replies
3
Views
1K
Replies
3
Views
1K
Replies
13
Views
2K
Replies
4
Views
1K
Replies
1
Views
2K
Back
Top