1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

An easy c question

  1. Jun 25, 2006 #1
    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;
    }
     
  2. jcsd
  3. Jun 25, 2006 #2
    How do I return the value a back to the main function.
     
  4. Jun 25, 2006 #3

    DaveC426913

    User Avatar
    Gold Member

    What problem are you having? Does the above not work?
     
  5. Jun 25, 2006 #4
    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.
     
  6. Jun 25, 2006 #5
    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);
    }
     
  7. Jun 25, 2006 #6
    Can anyone help me?
     
  8. Jun 25, 2006 #7
    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 (Text):

    #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
     
  9. Jun 25, 2006 #8

    DaveC426913

    User Avatar
    Gold Member

    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: An easy c question
  1. C question (Replies: 19)

  2. C++ question (Replies: 8)

  3. C question (Replies: 6)

Loading...