||运算和&&运算

||运算是发现有一个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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值