算术C ++运算符 [英] Arithmetic C++ Operators

查看:166
本文介绍了算术C ++运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在技术采访中只是问了一个问题,我有点困惑。



问题如下:



如果

  int i = -1,int j = -1,int k = -1 ,

,我们运行以下行:

  ++ i&&& ++ j&& ++ k 

i,j和k的新值是什么?我感到困惑的原因是,因为我们不把这个表达式赋给任何东西,它似乎不像和运算符应该有什么区别(只有增量运算符应该)。然而,运行一个简单的测试程序快速证明我错了。

解决方案

这里的关键是&&& 是短路的。



因此, ++ i 首先进行评估。它增加 i 并返回新值,它是 0 ,所以表达式的其余部分不被求值。



如果我没有错误,值应该是 0,-1,-1 >

I was just asked a question in a technical interview that I was a bit confused about.

The question was as follows:

If

int i = -1, int j = -1, and int k = -1, 

and we run the following line:

++i && ++j && ++k

what would be the new values of i, j, and k? The reason I was confused is that, since we are not assigning this expression to anything, it doesn't seem like the and operators should make any difference (only the increment operators should). However, running a simple test program quickly proved that I was mistaken. Could someone explain this to me, as I have never seen this exercise before.

解决方案

The key here is that && is short-circuiting.

So, ++i is evaluated first. It increments i and returns the new value, which is 0, so the rest of the expression doesn't get evaluated.

The values should be 0, -1, -1 if I'm not mistaken.

这篇关于算术C ++运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆