这是C语言中未定义的行为吗? [英] Is this an undefined behavior in C?

查看:93
本文介绍了这是C语言中未定义的行为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在gcc上运行我的C代码,以了解前/后增量运算符. 但是,我看到的结果不是我期望的.就像第6行一样,因为我是5,所以应该是

I am running my C code on gcc to understand pre/post increment operator. However the results that I see are not what I expected. Like for the line 6, since i is 5, it should have been

8 7 6 5 5

但是它是8 7 6 5 8

然后到最后一行,它显示14 14 14 14.有人可以解释这种现象吗?我曾期望 14 14 13 12

Then coming to the last line, it displays 14 14 14 14. Can someone please explain this behavior. I had expected 14 14 13 12

此编译器是否依赖?序列点上的printf函数的行为是否未定义?

Is this compiler dependent? Is the beahviour of printf function on sequence points undefined?

#include <stdio.h>

int main()
{
        i = 5;
        printf("%d %d %d %d %d \n", i, i++, i++, i++, i);
        printf("%d \n", ++i);
        printf("%d \n", ++i);
        printf("%d \n", ++i);
        printf("%d %d %d %d \n", i, ++i, ++i, ++i);

}

推荐答案

标准指出

在上一个序列点和下一个序列点之间,对象应具有其 通过对表达式的求值,存储值最多只能修改一次. 此外,只能访问先验值以确定 要存储的值.

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 accessed only to determine the value to be stored.

这些是找到序列点的地方:

And these are the places where you will find sequence points:

  • 在评估完整表达式(完整表达式 是一个表达式语句,或不是 任何较大的表达式中的子表达式);

  • at the end of the evaluation of a full expression (a full expression is an expression statement, or any other expression which is not a subexpression within any larger expression);

;和

最后一点的详细说明:函数调用中的逗号运算符不是 序列点,并且,之间的表达式可以按任意顺序求值.

An elaboration of the last point: the comma operators in a function call are not sequence points and the expressions between the ,s can be evaluated in any arbitrary order.

检查

Check this and this for better understanding.

printf("%d %d %d %d %d \n", i, i++, i++, i++, i);中,您在两个序列点之间多次写入同一内​​存位置,从而调用不确定的行为.

In printf("%d %d %d %d %d \n", i, i++, i++, i++, i);, you are writing to the same memory location more than once between two sequence points, thus invoking undefined behaviour.

这篇关于这是C语言中未定义的行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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