CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 23
  1. #1
    Join Date
    Nov 2010
    Posts
    81

    Changing function based on a condition?

    I was wondering if it's possible to have ONE function perform a different task, depending on some condition, or would I have to make separate functions? Here's my example:

    Code:
    		int x, y, z, product;
    
    		x = getData();
    		y = getData();
    		z = getData();
    
    int getData()
    {
    	int num;
    	cout	<< "Please enter a number: ";
    	cin	>> num;
    	return num;
    }
    That was an in-class exercise. BUT... can I have getData say something like "Please enter first number: " then "Please enter second number: ", etc? ... or would I need three separate functions saying three separate things? I am working on a different project, and if I can do this, it would be great! So... is there a way? I don't know enough yet to figure that out. By the way... just pointing me in the right direction is fine... I don't want to have the answer handed over - I want to learn how myself. Also, we haven't learned pointers or any of that stuff yet... just doing functions now.

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: Changing function based on a condition?

    Quote Originally Posted by LogicWavelength View Post
    I was wondering if it's possible to have ONE function perform a different task, depending on some condition, or would I have to make separate functions?
    Yes, it is possible.
    Whether you "have to make separate functions" or not as usual depends...
    Victor Nijegorodov

  3. #3
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Changing function based on a condition?

    Generally speaking, this is what function parameters are for.

  4. #4
    Join Date
    Feb 2011
    Location
    Chicago, IL
    Posts
    7

    Re: Changing function based on a condition?

    Yes, you can use the same function..pass parameters with the help of the function getdata() you are calling..hope this helps!!

  5. #5
    Join Date
    Nov 2010
    Posts
    81

    Re: Changing function based on a condition?

    ...so I can use a placeholder variable as a parameter to send the function different info... then based on the parameter, use an if statement to make the function cout something new?

    Code:
    int x, y, z, product, variable;
    
                    variable = 0;
    		x = getData(variable);
                    variable = 1;
    		y = getData(variable);
                    variable = 2;
    		z = getData(variable);
    
    int getData()
    {
    	int num;
    	if (variable = 0)
            {
            cout	<< "Please enter the first number: ";
    	cin	>> num;
            }
            else if.... etc, etc, etc.
    	return num;
    }

  6. #6
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Changing function based on a condition?

    Quote Originally Posted by LogicWavelength View Post
    ...so I can use a placeholder variable as a parameter to send the function different info... then based on the parameter, use an if statement to make the function cout something new?
    Just try it and see:
    Code:
    #include <iostream>
    
    using namespace std;
    
    int getData(int nWhichData)
    {
       const char* varName = "xyz";
       cout << "Please enter value for " << varName[nWhichData] << " : " ;
       int value;
       cin >> value;
       return value;
    }
    
    int main()
    {
       int x, y, z;
       x = getData(0);   
       y = getData(1);   
       z = getData(2);   
    }
    Regards,

    Paul McKenzie

  7. #7
    Join Date
    Nov 2010
    Posts
    81

    Re: Changing function based on a condition?

    Thanks Paul! That's actually over my head with some of the code you wrote... I actually got back to my computer and tried what I wrote before - and it worked... minus the assignment error I had in my function. I'm sure yours would work too... but if I handed in something that had that in there my professor would know I didn't do it! Can't wait until I understand what you wrote there.

  8. #8
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Changing function based on a condition?

    You should be covering arrays soon if you haven't already.

  9. #9
    Join Date
    May 2009
    Posts
    2,413

    Re: Changing function based on a condition?

    Quote Originally Posted by LogicWavelength View Post
    ...so I can use a placeholder variable as a parameter to send the function different info... then based on the parameter, use an if statement to make the function cout something new?
    ... or you can send the prompt string as a parameter to the input function.

    How you generalize a function by the use of parameters may differ. The lesson is that parametrisation is one major way of making code more abstract in order to make it more general. Isolate what differs and make it a parameter.

  10. #10
    Join Date
    Nov 2010
    Posts
    81

    Re: Changing function based on a condition?

    Quote Originally Posted by Lindley View Post
    You should be covering arrays soon if you haven't already.
    We actually did arrays first... I just don't understand what you mean or how that applies to this problem.... I didn't get the varName[nWhichData] part he wrote. I have a lot to learn, I know.

  11. #11
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Changing function based on a condition?

    Well then, which part is unclear?

  12. #12
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Changing function based on a condition?

    Maybe its clearer like this?

    Code:
    #include <iostream>
    
    using namespace std;
    
    int getData(int nWhichData)
    {
       const char varName[4] = "xyz";
       cout << "Please enter value for " << varName[nWhichData] << " : " ;
       int value;
       cin >> value;
       return value;
    }
    
    int main()
    {
       int x, y, z;
       x = getData(0);   
       y = getData(1);   
       z = getData(2);   
    }
    This uses array semantics rather than pointer semantics. It is morally equivalent. There are subtle differences between the two, but nothing you need to worry about.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  13. #13
    Join Date
    Nov 2010
    Posts
    81

    Re: Changing function based on a condition?

    ummm... yea that part. I don't understand how that array solution really works. I mean, I see what it does, but I'd never have thought of that. Here's some snippets from my actual (now, finished) project:

    Code:
    		//--GETTING DATA FROM USER--//
    		int foo = 0;
    		studio = getData(foo);
    		foo = 1;
    		oneBed = getData(foo);
    		foo = 2;
    		twoBed = getData(foo);
    and here is the function definition:

    Code:
    int getData(int foo)
    {
    	int num;
    	if (foo == 0)
    	{
    		cout	<< "How many studio apartments?: ";
    		cin		>> num;
    	}
    	else if (foo == 1)
    	{
    		cout	<< "How many one-bedroom apartments?: ";
    		cin		>> num;
    	}
    	else if (foo == 2)
    	{
    		cout	<< "How many two-bedroom apartments?: ";
    		cin		>> num;
    	}
    
    	return num;
    }
    EDIT: On a umpteenth look at it, I see that you are using the array to send the 0, 1, 2 to the function parameter rather than manually assigning it like I did... correct? ...and that would allow the program to call those specific actions of the function later if needed, whereas my foo is now stuck assigned to 2... correct?
    Last edited by LogicWavelength; February 22nd, 2011 at 12:01 PM.

  14. #14
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Changing function based on a condition?

    Code:
    		//--GETTING DATA FROM USER--//
    		int foo = 0;
    		studio = getData(foo);
    		foo = 1;
    		oneBed = getData(foo);
    		foo = 2;
    		twoBed = getData(foo);
    There's no need to assign a value to a variable just to pass it. Since the function is making a copy of its argument anyway (pass-by-value), you can just pass the constant directly. So this is equivalent to:

    Code:
                    //--GETTING DATA FROM USER--//
    		studio = getData(0);
    		oneBed = getData(1);
    		twoBed = getData(2);
    regardless of what's in getData() (and assuming you don't need the fact that foo == 2 later in the main function of course).

    Code:
    int getData(int foo)
    {
    	int num;
    	if (foo == 0)
    	{
    		cout	<< "How many studio apartments?: ";
    		cin		>> num;
    	}
    	else if (foo == 1)
    	{
    		cout	<< "How many one-bedroom apartments?: ";
    		cin		>> num;
    	}
    	else if (foo == 2)
    	{
    		cout	<< "How many two-bedroom apartments?: ";
    		cin		>> num;
    	}
    
    	return num;
    }
    We can use an array in place of your if/else structure here, because the only difference between the three conditions is the type of apartment, and because your valid foo values are conveniently array-friendly anyway. This is simply a matter of condensing code, it doesn't change the behavior at all:

    Code:
    int getData(int foo)
    {
            const std::string apttypes[3] = {"studio", "one-bedroom", "two-bedroom"};
            int num;
            assert(foo >= 0 && foo < 3);
            cout << "How many " << apttype[foo] << " apartments?: ";
            cin >> num;
            return num;
    }
    I added the assert() to catch any invalid parameters. Note this check is only done when debugging; an optimized build will omit it (that's how assert works).

    We could have made apttype an array of const char*s rather than std::strings, it wouldn't make a difference in this case.
    Last edited by Lindley; February 22nd, 2011 at 12:09 PM.

  15. #15
    Join Date
    Nov 2010
    Posts
    81

    Re: Changing function based on a condition?

    I just realized, by looking at your examples, that my function call was over-complicated. Here is a better version. Sorry for the noob-ness.

    Code:
    		//--GETTING DATA FROM USER--//
    		studio = getData(0);
    		oneBed = getData(1);
    		twoBed = getData(2);
    EDIT: I posted that without seeing your response, Lindley! Haha...

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured