语言是否需要preIncrement(++ x)和postIncrement(x ++) [英] whether a language needs preIncrement (++x) and postIncrement (x++)

查看:66
本文介绍了语言是否需要preIncrement(++ x)和postIncrement(x ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从未在实际代码中看到预增后增的用例.我最常看到的地方是拼图.
我的看法是,它引入了更多的混乱,而不是有用的.

I have never seen the usecase for pre-increment and post-increment in actual code. The only place i see them most often are puzzles.
My opinion is, it introduces more confusion rather than being useful.

  • 是否有任何实际的用例场景
  • 不能通过使用+ =

  • is there any real use case scenario for this
  • can't this can be done by using +=

y = x++

y = x
x += 1

推荐答案

这只是编写相同内容的一种较短的方法,只会使那些不了解C的人感到困惑.(a) .可以用相同的论据来代替:

It's just a shorter way of writing the same thing and it's only confusing to those who don't deeply understand C (a). The same argument could be made for replacing:

for (i = 0; i < 10; i++)
    printf ("%d\n", i);

具有:

i = 0;
while (i < 10) {
    printf ("%d\n", i);
    i = i + 1;
}

因为任何for也可以用while完成,或者:

since any for can also be done with while, or:

i = 0;
loop: if (i < 10) {
    printf ("%d\n", i);
    i = i + 1;
    goto loop;
}

因为任何循环构造都可以根据条件和goto构建.但是(我希望)你不会那样做,对吗?

since any loop construct can be built out of conditions and goto. But (I'm hoping) you wouldn't do that, would you?

(a)有时我想以简单的陈述和副作用向我的学生解释这一点,这使C代码更简洁,可读性通常没有损失或损失很小.

(a) I sometimes like to explain this to my students as simple statements and side effects, something that allows C code to be more succinct with usually no or minimal loss in readability.

对于声明:

y = x++;

声明x分配给y,其副作用是x之后会增加. ++x是相同的,只是副作用是事先发生的.

the statement is assigning x to y with the side effect that x is incremented afterwards. ++x is the same, it's just that the side effect happens beforehand.

类似地,赋值的副作用是它将赋值为赋值,这意味着您可以执行以下操作:

Similarly, the side effect of an assignment is that it evaluates as the value assigned, meaning you can do things like:

while ((c = getchar()) != -1) count++;

并使之类似于:

42;

完全有效,但无用的C语句.

perfectly valid, but useless, C statements.

这篇关于语言是否需要preIncrement(++ x)和postIncrement(x ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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