小编GN_*_*oub的帖子

C++:在评估顺序运算符时忽略括号

首先,我必须说这里提出的问题已经解决了,我想知道:

  • 我误解了什么,
  • 如果编译器有错误(我知道这很少见)(它是gcc 4.8.4).

我想计算一个二维向量的范数,其坐标仅在那一刻计算.比方说,我想计算|| (x0,y0) - (x1,y1)|| ,通过公式sqrt((x0-x1)**2 +(y0-y1)**2).只需要保存结果.

出于性能原因,方块是通过自乘法完成的,我希望变量和变量访问只能进行一次.我希望总计在运行时有效,并以某种方式优雅地编码.我想到了三种可能性:

  • 重复两次x0 - x1y0 - y1,并希望compilator的优化步骤将检测到重复,
  • 使用内联函数,
  • 一起使用缓冲变量和顺序运算符.

我决定尝试最后一个选项.


现在考虑以下代码:

#include <cmath>
#include <stdio.h>

int main (void)
{
    float x0 (-1), x1 (2), y0 (13), y1 (9), result, tmp;

    result = std::sqrt ((tmp = x0 - x1, tmp * tmp) + (tmp = y0 - y1, tmp * tmp));
    printf ("%f\n", result);
}
Run Code Online (Sandbox Code Playgroud)

我知道我必须得到5.000000,但我得到了5.656854,这是sqrt((y0-y1)**2 +((y0-y1)**2)).

我可以得到想要的结果:

#include <cmath>
#include <stdio.h>

int main …
Run Code Online (Sandbox Code Playgroud)

c++ comma parentheses g++4.8

2
推荐指数
1
解决办法
139
查看次数

标签 统计

c++ ×1

comma ×1

g++4.8 ×1

parentheses ×1