Stupid C ++ question about if-else

I have this code:

#include <iostream>
using namespace std;

int main()

{ char c='6';
    if(c == '+' || '-' || '*' || '^' || '/' || '%')
    {
        cout<<"good";
    }
    else {cout<<"bad";}
    return 0;
} 

I want to write “good” if char is “+” or “-” etc., and write “bad” if char is something else. But this code always writes “good” with any char.

Where is the problem? Thank.

+3
source share
3 answers

if(c == '+' || '-' || '*' || '^' || '/' || '%')

analyzes on

if( (c == '+') || ('-'!=0) || ('*'!=0 || ('^'!=0) || ('/'!=0) || ('%'!=0))

It will always evaluate true because the '-' is indeed non-zero. Of course, this is a kind of flaw with a security type that char "degrades" to a boolean value and evaluates to true. (The correct safe solution would be to simply not compile your code unless you explicitly use it).

, c . . , :

C strchr:

if( strchr( "+-*^/%", c ) != NULL )

switch

switch (c )
{
  case '+': case '-': case '*': case '^': case '/': case '%':
      // true logic
  break;

  default:
   // false logic
};

(overkill , ).

:: BitSet

"", , , , .

// one-time setup
std::bitset<256> myCharSet;
myCharSet.set('+');
myCharSet.set('-');
myCharSet.set('*');
myCharSet.set('^');
myCharSet.set('/');
myCharSet.set('%');

// subsequently
if( myCharSet.test( static_cast<unsigned char>(c) ) )
{
   // true logic
}
else
{
  // false logic
}

, .   static bool charset [256] = {false};   static bool init = false;   if (! init)   {       charset ['+'] = true;// .       init = true;   }

if( charset[ static_cast<unsigned char>(c) ] )
{
  // true logic
}
else
{
    // false logic
}

, , , ( , 0 , , , ),

, .

(, ++ std::string, find std:: find), .

+16

, :

if(c == '+' || c == '-' || c == '*' || c == '^' || c == '/' || c == '%')

:

switch (c)
{
    case '+': case '-': case '*' : case '^' : case '/' : case '%':
        cout << "good\n"; break;
    default: cout << "bad\n"; break;
}
+8

he should be

 if(c == '+' || c == '-' || c == '*' || c == '^' || c == '/' || c == '%')
 ...

otherwise, the expression always evaluates to true. Any of these characters has a value other than 0, so true for C ++.

+6
source

Source: https://habr.com/ru/post/1793044/


All Articles