Solving a C Local Variable Issue

  • Thread starter Thread starter Nothing000
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
7 replies · 2K views
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;
}
 
Physics 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.