前缀和后缀运算符有什么区别? [英] What is the difference between prefix and postfix operators?

查看:37
本文介绍了前缀和后缀运算符有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码打印的值为 9.为什么?这里 return(i++) 将返回一个值 11 并且由于 --i 值应该是 10 本身,谁能解释一下这是如何工作的?

The following code prints a value of 9. Why? Here return(i++) will return a value of 11 and due to --i the value should be 10 itself, can anyone explain how this works?

#include<stdio.h>
main()
{
    int i= fun(10);
    printf("%d
",--i);
}

int fun (int i)
{
    return(i++);
}

推荐答案

++ 的后缀和前缀版本之间存在很大区别.

There is a big difference between postfix and prefix versions of ++.

在前缀版本(即++i)中,i的值递增,表达式的值为newstrong> i 的值.

In the prefix version (i.e., ++i), the value of i is incremented, and the value of the expression is the new value of i.

在后缀版本(即i++)中,i的值是递增的,但表达式的值是原始i 的值.

In the postfix version (i.e., i++), the value of i is incremented, but the value of the expression is the original value of i.

我们一行一行地分析下面的代码:

Let's analyze the following code line by line:

int i = 10;   // (1)
int j = ++i;  // (2)
int k = i++;  // (3)

  1. i 设置为 10(简单).
  2. 这一行有两件事:
    • i 增加到 11.
    • inew 值复制到j 中.所以 j 现在等于 11.
  1. i is set to 10 (easy).
  2. Two things on this line:
    • i is incremented to 11.
    • The new value of i is copied into j. So j now equals 11.
  • i 增加到 12.
  • i(即11)的原始值复制到k中.所以 k 现在等于 11.
  • i is incremented to 12.
  • The original value of i (which is 11) is copied into k. So k now equals 11.

所以在运行代码之后,i 将是 12,但 jk 都是 11.

So after running the code, i will be 12 but both j and k will be 11.

同样的东西也适用于 -- 的后缀和前缀版本.

The same stuff holds for postfix and prefix versions of --.

这篇关于前缀和后缀运算符有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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