Colin's Blog

Recent content on Colin's Blog

马上订阅 Colin's Blog RSS 更新: https://blog.oyyko.com/index.xml

A strange way to compute GCD

finalwind42@gmail.com (Oyyko)
2021年11月18日 08:00

A strange way to compute GCD in one line

1int gcd(int x, int y)2{3    while (x ^= y ^= x ^= y %= x)4        ;5    return y;6}

有趣的是:这种写法在CPP17之前是ub(在同一个语句中多次改变一个变量的值,且反复使用该变量的值,为ub 因为标准没有规定求值的顺序),在CPP17中,对于求值的顺序做了进一步的规定,从而这种写法具备了可移植性。