关于if(b);与if(b==true);的区别
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string s,result_str;
bool has_punct=false;
char ch;
cout<<"输入一段文字"<<endl;
getline(cin,s);
for(string::size_type index=0;index<s.size();index++)
{
ch=s[index];
if(ispunct(ch)==true)
{
has_punct=true;
}
else
result_str+=ch;
}
if(has_punct)
cout<<result_str;
else
cout<<s;
return 0;
}
Synopsis:
#include <stdio.h>
int ispunct(int c);
Description:
The function returns nonzero if c is any of:
! " # % & ' ( ) ; < = >> ?
[ \ ] * + , - . / : ^ _ {
[解决办法]
} ~
Return Value
The function returns nonzero if c is punctuation otherwise this will return zero which will be equivalent to false.
Example
#include <stdio.h>
int main() {
if( ispunct( '%' ) )
{
printf( "Character % is a punctuation\n" );
}
if( ispunct( 'A' ) )
{
printf( "Character A is a punctuation\n" );
}
return 0;
}
It will proiduce following result:
Character % is a punctuation
6.4/4 The value of a condition that is an initialized declaration in a statement other than a switch statement is the
value of the declared variable contextually converted to bool (Clause 4). If that conversion is ill-formed, the
program is ill-formed. The value of a condition that is an initialized declaration in a switch statement is the
value of the declared variable if it has integral or enumeration type, or of that variable implicitly converted
to integral or enumeration type otherwise. The value of a condition that is an expression is the value of the
expression, contextually converted to bool for statements other than switch; if that conversion is ill-formed,
the program is ill-formed. The value of the condition will be referred to as simply “the condition” where the
usage is unambiguous.
[解决办法]
因为是int所以等效,不等效的情况是你代码引起未定义行为。不过还是尽量别多此一举==true。
如果b是定义了explicit bool()但没定义和bool之间的==操作的类型,if(b)没问题而if(b == true)就不行。
[解决办法]
区别就是 if (ispunct) 对所有非零值都成立;而 if (ispunct==true) 只有当 ispunct 返回值为 1 的时候才成立,这是因为 == 要求其操作数发生 integral promotion,所以 true 变成了 1,作为一个整形数字参与比较,就好像写 if (ispunct == 1),错误显而易见。