Return -1

Hi guys.
How can I return 255 in this function when
char& is not const???


1
2
3
4
5
6
7

char& myString::operator[] (const int index) 
{
    if (index < this->len || index> this->len)
      return 255; 
    return this->s[index]; 
}

return unsigned char
There are a few problems with this code:

1
2
3
4
5
6
char& myString::operator[] (const int index) 
{
    if (index < this->len || index> this->len)  // this is saying that 'len' is the only possible index
      return 255;   // you cannot return a literal 255 as a non-const reference
    return this->s[index]; 
}


The reason you can't return a literal is simple. What if someone tries to do this:

 
mystr[i] = 'v';


where 'i' is an out of range index. You'd effectively be trying to do 255 = 'v'; which is nonsense.

If you really want to do this, you'll need to have a dummy value:

1
2
3
4
5
char& myString::operator[] (const int index) 
{
    static char dummy;
    if ( /*index is out of bounds*/ )
      return dummy;


However note that you cannot really reliably specify what dummy is. You can initialize it with -1, but it can be changed at any time by the user doing this:

1
2
3
// assuming 'i' is out of bounds
mystr[i] = 'v';  // changes dummy to 'v'
cout << mystr[i];  // will print 'v', not -1 / 255 


That's besides the point that char's range is only [-128..127], so it can't even represent 255 anyway.


Really the best way to handle an out of range error in this situation is to throw an exception.
(Or use pointers, and return NULL on error...) but I think exceptions are the way to go too...
Thanks for your answers guys.

Sure thing that exceptions are the way better than monkeying around with return values of different data types.
I just got a teacher who really waned us to return 255 as a char and then cast it as a int...

1
2
    char num = 255;
    cout << int(num) << endl; 

       -1                        
Topic archived. No new replies allowed.