-2

I have a problem with my code. I wrote a bool function above int main():

bool currency_(const char c)
{
    while (c==' ')
    {
        if (c==('p', 't', 'e', 'd'))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

I expect the program to work, but instead while compiling it shows "control reaches end of non-valid function".

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97

4 Answers4

6

Your function makes no sense.

If c is a space character, your if statement (had you written it correctly, which you didn't) will always evaluate as false.

And if c is not a space character, your function exits with an undefined return value.

And your while is useless, since the function never modifies c.

You probably meant to write something like this instead:

bool currency_(const char c)
{
    if (c =='p' || c == 't' || c == 'e' || c == 'd')
    {
        return true;
    }
    else
    {
        return false;
    }
}

Or simply

bool currency_(const char c)
{
    return (c =='p' || c == 't' || c == 'e' || c == 'd');
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
3

Like this

if (c == 'p' || c == 't' || c== 'e' || c == 'd')

It's not a good idea to make up code and hope it's correct C++. It rarely works.

But even with this correction your other problem about control reaching the end of a non-void function remains. What do you expect your code to return if c does not equal ' '?

And then you have another problem which is that if c equals ' ' then it cannot equal 'p', 't', 'e' or 'd'. So your code has some logic problems as well.

john
  • 85,011
  • 4
  • 57
  • 81
3
while (c==' ')
    {
        if (c==('p', 't', 'e', 'd'))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

If c != ' ', you never enter the body of your while loop, and reach end of non-void function, without returning anything, invoking undefined behavior.

Also, if (c==('p', 't', 'e', 'd')) doesn't do what you think it does. You should either chain || operator, like so

if(c == 'p' || c == 't' || c == 'e' || c == 'd'){...}

Or, you could use std::array and std::find.

constexpr std::array<char,4> characters{'p', 't', 'e', 'd'};
if(std::find(characters.cbegin(), characters.cend(), c) != characters.cend()) {...}
Kaldrr
  • 2,780
  • 8
  • 11
1

put those chars in a vector and try to find c in it:

std::vector<char> options{'p', 't', 'e', 'd'};
bool currency_(const char c)
{

    if (std::find(options.begin(), options.end(), c) != options.end())
    {
        return true;
    }
    else
    {
        return false;
    }

}

or even better just return the result of std::find directly:

bool currency_(const char c)
{
    return (std::find(options.begin(), options.end(), c) != options.end())
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97