创建并验证指向"if"语句的指针

fog*_*bit 4 c++ pointers if-statement

这段代码是否正确?

void foo ( int* p )
{
  if ( int* p2 = p ) // single "="
  {
    *p2++;
  }
}
Run Code Online (Sandbox Code Playgroud)

我一直以为它不是,但最近我在同事的矿源中看到过这样的代码.

如果"p"为NULL怎么办?MS VS 2008工作正常,但显示"警告C4706:条件表达式中的赋值".

谢谢.

seh*_*ehe 7

警告assignment within conditional expression通常由编译器发出,以防止您编写的情况

 if (a = b) 
 {
Run Code Online (Sandbox Code Playgroud)

在哪里你的意思

 if (a == b) // big difference!
 {
Run Code Online (Sandbox Code Playgroud)

在您的示例中,"赋值警告"实际上是伪造的,因为它实际上不是赋值,而是初始化:

 {
      int *p2 = p;
      if (p2)
      {

      }
 }
Run Code Online (Sandbox Code Playgroud)

并且没有风险你真的想要语法错误(int *p2 == p?!)而不是:)

你的帖子的其余部分是完全有效的C++ 03(及更高版本),只是做了它所说的1.


1 (就持久效果而言,并不多,因为

  • p2被解除引用而没有用它任何事情
  • p2增加而没有任何事情,

但我猜这只是示例代码?如果不明显,*p2++相当于*p2; p2++;)