functions that don't always return a value

Hi,

This might be a simple question but I didn't know how to word it exactly...
I want a function to return a value only if the parameters are satisfied:

int Color ( string colorIn )
{
int myColor;

if ( colorIn == "black" || colorIn == "Black" || colorIn == "BLACK" )
{
myColor = 0;
}

if ( colorIn == "brown" || colorIn == "Brown" || colorIn == "BROWN" )
{
myColor = 1;
}
else
{
cout << "Please enter a proper color. \n";
}

return myColor;
}


in the case that it's anything other than the two colors currently specified I don't want to return myColor.
Is there any way to exclude the else from returning a value?

thanks,
~mark
throw an exception.
closed account (z05DSL3A)
...or consider returning something like -1 to indicate an error.
You are splitting up an input operation arbitrarily, and that is tripping you up.

Your function should validate a color, nothing else. The Input and Validate part of your code only uses the function to validate the input.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <algorithm>
#include <cctype>
#include <functional>
#include <iostream>
using namespace std;

// This is our list of colors.
const char* VALID_COLORS[] =
  { 
  "black",
  "brown"
  };

// These are indices into our list of colors.
// Notice how the LAST index indicates an invalid color
typedef enum
  {
  color_black,
  color_brown,
  color_invalid
  }
  valid_color_t;

// This function transforms a color name into a valid_color_t
//
valid_color_t is_color_valid( string color )
  {
  // Transform string to lowercase for comparisons
  transform( color.begin(), color.end(), color.begin(), ptr_fun <int, int> ( tolower ) );

  // Locate the 
  return static_cast <valid_color_t> (
    find( VALID_COLORS, VALID_COLORS + color_invalid, color ) - VALID_COLORS
    );
  }

int main()
  {
  // This is the result of our Input And Validate operation
  valid_color_t validated_color;

  // The block that follows here is the Input And Validate operation
  // First, tell the user what we want
  cout << "Please enter a color (black or brown): " << flush;
  while (true)
    {
    // Get the user's response
    string s;
    getline( cin, s );

    // Validate the user's response
    validated_color = is_color_valid( s );

    // If the user's response passed our validation, we are done
    if (validated_color != color_invalid) break;

    // Otherwise, give the user a little more explicit instruction and try again
    cout << "Please enter either BLACK or BROWN: " << flush;
    }

  // Now that we have a validated color from the user, we can use it
  cout << "Good job! You entered " << VALID_COLORS[ validated_color ] << "!\n";
  return 0;
  }

Hope this helps.
Topic archived. No new replies allowed.