||运算是发现有一个false时,会继续往下计算表达式,直到碰到一个true时截止
&&运算是发现一个true时,不断往下计算,直到碰到一个false的结果
看下列代码
// Example program
#include <iostream>
#include <string>
using namespace std;
bool Func1()
{
cout << "func 1 call" << endl;
return false;
}
bool Func2()
{
cout << "func 2 call" << endl;
return true;
}
int main()
{
cout << "---------------test 1------------" << endl;
if (Func1() || Func2()) {
cout << "|| is true." << endl;
} else {
cout << "|| is false." << endl;
}
cout << "---------------test 2------------" << endl;
if (Func2() || Func1()) {
cout << "|| is true." << endl;
} else {
cout << "|| is false." << endl;
}
cout << "---------------test 3------------" << endl;
if (Func1() && Func2()) {
cout << "&& is true." << endl;
} else {
cout << "&& is false." << endl;
}
cout << "---------------test 4------------" << endl;
if (Func2() && Func1()) {
cout << "&& is true." << endl;
} else {
cout << "&& is false." << endl;
}
return 0;
}
结果输出
---------------test 1------------
func 1 call
func 2 call
|| is true.
---------------test 2------------
func 2 call
|| is true.
---------------test 3------------
func 1 call
&& is false.
---------------test 4------------
func 2 call
func 1 call
&& is false.
对比test 1和test 2,|| 运算检查到true时就会停止
对比test 3和test 4,&&运算检查到false时就会停止
基于此,我们可以考虑写出下列代码,一个取文件名的例子
std::string GetRelativePath(std::string& path)
{
if (path.empty() || (path.back() == '/')) { // 当path为非空时,再确定是不是目录
return path;
}
std::string rPath = path;
std::string::size_type pos = path.rfind('/');
if (pos != std::string::npos) {
pos++;
rPath = path.substr(pos);
}
return rPath;
}