500字范文,内容丰富有趣,生活中的好帮手!
500字范文 > C++中i++和++i的区别

C++中i++和++i的区别

时间:2020-05-20 23:21:31

相关推荐

C++中i++和++i的区别

答:理论上++i更快,实际与编译器优化有关,通常几乎无差别。

i++实现的代码为:

//i++实现代码为:int operator++(int) {int temp = *this; ++*this;return temp;}//返回一个int型的对象本身12345671234567

++i的实现代码:

// ++i实现代码为:int& operator++(){*this += 1;return *this;}//返回一个int型的对象引用123456123456

i++和++i的考点比较多,简单来说,就是i++返回的是i的值,而++i返回的是i+1的值。也就是++i是一个确定的值,是一个可修改的左值,如下使用:

cout << ++(++(++i)) << endl;cout << ++ ++i << endl;1212

可以不停的嵌套++i。

这里有很多的经典笔试题,一起来观摩下:

int main(){int i = 1;printf("%d,%d\n", ++i, ++i); //3,3printf("%d,%d\n", ++i, i++); //5,3printf("%d,%d\n", i++, i++); //6,5printf("%d,%d\n", i++, ++i); //8,9system("pause");return 0;}12345678910111234567891011

首先是函数的入栈顺序从右向左入栈的,计算顺序也是从右往左计算的,不过都是计算完以后在进行的压栈操作:

对于第5行代码,首先执行++i,返回值是i,这时i的值是2,再次执行++i,返回值是i,得到i=3,将i压入栈中,此时i为3,也就是压入3,3;

对于第6行代码,首先执行i++,返回值是原来的i,也就是3,再执行++i,返回值是i,依次将3,5压入栈中得到输出结果

对于第7行代码,首先执行i++,返回值是5,再执行i++返回值是6,依次将5,6压入栈中得到输出结果

对于第8行代码,首先执行++i,返回i,此时i为8,再执行i++,返回值是8,此时i为9,依次将i,8也就是9,8压入栈中,得到输出结果。

上面的分析也是基于vs搞的,不过准确来说函数多个参数的计算顺序是未定义的(the order of evaluation of function arguments are undefined)。笔试题目的运行结果随不同的编译器而异。

参考:/bs_faq2.html#evaluation-order

下面是使用其他编译器输出的结果:

//------ C++ version ------#include <cstdio>int main(){int i = 1;printf("%d %d\n", ++i, ++i);printf("%d %d\n", ++i, i++);printf("%d %d\n", i++, i++);printf("%d %d\n", i++, ++i);return 0;}//------ C version ------#include <stdio.h>int main(){int i = 1;printf("%d %d\n", ++i, ++i);printf("%d %d\n", ++i, i++);printf("%d %d\n", i++, i++);printf("%d %d\n", i++, ++i);return 0;}123456789101112131415161718192223123456789101112131415161718192223

上面是参考的执行代码。

gcc-5.1(C++) gcc-5.1(C++14) gcc-5.1(C) 的执行结果:

3 35 36 58 912341234

gcc-4.3.2(C++) clang-3.7(C++) clang-3.7(C) 的执行结果

2 34 45 67 912341234

gcc-5.1(C99 strict) 的编译结果:编译不通过。

C99 strict prog.c: In function 'main':prog.c:6:28: error: operation on 'i' may be undefined [-Werror=sequence-point]printf("%d %d\n", ++i, ++i);^prog.c:7:29: error: operation on 'i' may be undefined [-Werror=sequence-point]printf("%d %d\n", ++i, i++);^prog.c:8:29: error: operation on 'i' may be undefined [-Werror=sequence-point]printf("%d %d\n", i++, i++);^prog.c:9:28: error: operation on 'i' may be undefined [-Werror=sequence-point]printf("%d %d\n", i++, ++i);^cc1: all warnings being treated as errors12345678910111213141234567891011121314

由上可见,这种比较毫无意义。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。