[C++]括号使用小技巧

1.前言

  对于一般的赋值语法,例如

int a = 0;

  但你知道吗?使用括号可以同时写很多类型,编译器一般默认括号内最后一个类型为赋值类型,例如

//编译器会选择最后一位进行赋值
int a = (100,200,300,0);

  此时,a的值就是0。

2.改变函数返回值

  有如下三个函数,返回值类型分别为void、int、bool

void Func1()
{
    std::cout<<"this function 1 return void"<<std::endl;
    return;
}

int Func2()
{
    std::cout<<"this function 2 return int"<<std::endl;
    return 0;
}

bool Func3()
{
    std::cout<<"this function 3 return bool"<<std::endl;
    return false;
}

  然后,在main里的调用

int main()
{
    Func1();
    Func2();
    Func3();
    
    return 0;
}

  结果如下:  

  this function 1 return void
  this function 2 return int
  this function 3 return bool

  然后对它们进行改动一下

int main()
{
    Func1();
    Func2();
    Func3();

    std::cout<<"================================================================"<<std::endl;

    int ret1 = (Func1(),100);
    std::cout<<"ret1 value: "<<ret1<<std::endl;

    bool ret2 = (Func2(),false);
    std::cout<<"ret2 value: "<<ret2<<std::endl;

    float ret3 = (Func3(),true);
    std::cout<<"ret3 value: "<<ret3<<std::endl;


    return 0;
}

  然后结果就变成了

  this function 1 return void
  this function 2 return int
  this function 3 return bool
  ================================================================
  this function 1 return void
  ret1 value: 100
  this function 2 return int
  ret2 value: 0
  this function 3 return bool
  ret3 value: 1

posted @ 2024-08-22 17:20  PangCoder  阅读(39)  评论(0)    收藏  举报