相关疑难解决方法(0)

"C++编程语言"第4版第36.3.6节中的代码是否有明确定义的行为?

在Bjarne Stroustrup的"C++编程语言"第4版36.3.6 STL类操作部分中,以下代码用作链接示例:

void f2()
{
    std::string s = "but I have heard it works even if you don't believe in it" ;
    s.replace(0, 4, "" ).replace( s.find( "even" ), 4, "only" )
        .replace( s.find( " don't" ), 6, "" );

    assert( s == "I have heard it works only if you believe in it" ) ;
}
Run Code Online (Sandbox Code Playgroud)

断言失败gcc(看到它直播)和Visual Studio(看到它的实时),但它在使用Clang时没有失败(请参见实时).

为什么我会得到不同的结果?这些编译器是否错误地评估了链接表达式,或者此代码是否表现出某种形式的未指定 …

c++ operator-precedence language-lawyer unspecified-behavior c++11

95
推荐指数
1
解决办法
9797
查看次数

给定代码中的未定义行为?

如果在呼叫之前将p的值初始化为5,则f(p,p)的返回值是多少?请注意,第一个参数通过引用传递,而第二个参数按值传递.

int f (int &x, int c) {
       c = c - 1;
       if (c==0) return 1;
       x = x + 1;
       return f(x,c) * x;
}
Run Code Online (Sandbox Code Playgroud)

选项包括:

  1. 3024
  2. 6561
  3. 55440
  4. 161051

我试着解释一下:


在这段代码中,将有四个带参数(6,4),(7,3),(8,2)和(9,1)的递归调用.最后一次调用返回1.但是由于通过引用传递,所有先前函数中的x现在是9.因此,f(p,p)返回的值将是9*9*9*9*1 = 6561.


这个问题来自竞争性考试GATE,(见Q.no.-42).答案密钥由GATE"Marks to all"给出(表示没有选项正确.)key set-C,Q.no.-42.在某处解释为:

在GATE 2013中,所有人都给出了标记,因为C/C++中的相同代码会产生未定义的行为.这是因为*它不是C/C++中的序列点.必须替换正确的代码

return f(x,c) * x;
Run Code Online (Sandbox Code Playgroud)

 res = f(x,c);
 return res * x;
Run Code Online (Sandbox Code Playgroud)

但是给定的代码工作正常.GATE的关键是错的吗?或者问题确实是错误的?

c c++ undefined-behavior unspecified-behavior c++11

5
推荐指数
2
解决办法
344
查看次数