c语言输出函数遇到自增,printf函数输出自增变量

看了楼上的回答,这种情况应该算是未定义行为,取决于编译器实现。下面补充一些参考:

1) sequence point from wikipedia

在C与C++程序设计语言中,表达式的值依赖于它的子表达式的求值顺序。增加更多的顺序点限制了可能的求值顺序,能保证有一个一致结果。

其中的一个sequence point是函数调用时的函数入口点。函数实参的求值顺序未指定,但顺序点意味着这些实参求值的副作用在进入函数时都已经完成。表达式f(i++) + g(j++) + h(k++),调用f(), g(), h()的顺序未指定,i, j, k的自增顺序也未指定。函数调用f(a,b,c)的实参列表不是逗号运算符,a, b, and c的求值顺序未指定。

C语言的所有sequence point可以参考上面链接,但是可以发现,上面的例子所涉及的关键部分并没有包含确定的sequence point,因此行为时undefined。

gcc有个-Wsequence-point选项可以用来对违反c/c++ sequence point规则而引发的未定义行为进行警告。经过测试,gcc -Wsequence-point 1.c 编译上述代码都会发现下面的警告:

1.c:4:27: warning: operation on ‘i’ may be undefined [-Wsequence-point]

printf("%d %d\n", ++i,++i);

^

-Wsequence-point说明也可以解释楼主的疑惑:

It is not specified when between sequence points modifications to the values of objects take effect. Programs whose behavior depends on this have undefined behavior; the C and C++ standards specify that "Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.". If a program breaks these rules, the results on any particular implementation are entirely unpredictable.

Since the increment/decrement operator modifies its operand, use of such an operand more than once within the same expression can produce undefined results. For example, in expressions such as x − ++x, it may not be clear to a user in what sequence the subtraction and increment operations should be performed. Such expressions generally invoke undefined behavior, and should be avoided.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值