Search code examples
c++booleannegative-number

How to figure out if the first index in an array is a negative sign


I am trying to write a bool function that looks at the first index in an array which contains a positive or negative number and classifies if it is a negative sign (i.e. -). If it is a negative Sign it returns false everything else returns true. I am trying to figure out how to compare the negative sign. The following code give an error because of the '-'

    bool BigNum::get_positive() const
{
char '-';
if(digits[0] == '-')
{
    return false;
}
else
{
    return true;
}
}

Solution

  • char '-';
    

    The compiler thinks you're trying to declare a char, but that's not a valid declaration.

    Your entire function could be replaced with:

    return (digits[0] != '-');
    

    Of course, this is assuming that [0] is a valid index of digits. If not, bad things will happen. If you know the length of the array, you can do a check like this:

    if( digits_length < 1 )
      return false;
    return (digits[0] != '-');