具有静态和指针的 C 代码

标签 c output undefined-behavior

我的代码是:

 main()
{
  static int arr[]={97,98,99,100,101,102,103,104};
  int *ptr=arr+1;
  print(++ptr,ptr--,ptr,ptr++,++ptr);
}
print(int*a,int*b,int*c,int*d,int*e)
{
    printf("%d %d %d %d %d",*a,*b,*c,*d,*e);

}

输出为:100 100 100 99 100

我无法理解这个问题。

请有人向我解释一下这段代码及其输出。

谢谢。

最佳答案

首先,这一行包含未定义的行为

print(++ptr,ptr--,ptr,ptr++,++ptr);

因为它多次使用属于具有副作用的表达式一部分的变量,但没有达到 sequence point .

In the code static keyword is used so i thought that each time it would take a different input.

在此示例中,存在或不存在 static 关键字没有任何区别,因为代码从不打印指针的值,仅打印该指针指向的内存内容。

您可以通过将每个具有副作用的表达式移动到单独的行来删除未定义的行为,如下所示:

static int arr[]={97,98,99,100,101,102,103,104}; // static can be removed
int *ptr=arr+1;         // Start at index 1
printf("%d\n", *++ptr); // Move to index 2, prints 99 
printf("%d\n", *ptr--); // Print 99, move to index 1
printf("%d\n", *ptr);   // Print 98, stay at position 1
printf("%d\n", *ptr++); // Print 98, move to position 2
printf("%d\n", *++ptr); // Move to position 3, print 100

( demo )

现在输出不同(并且正确):

99
99
98
98
100

这是您应该根据预增量/减量和后增量/减量运算符的语义获得的输出。

关于具有静态和指针的 C 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20264407/

相关文章:

c - BCD如何转换为十进制?

python - python中的多行输入不同输出

C - #define 的意外输出

c - 字符串比较失败

java - 在 Java 中使用 C 代码的快速步骤

c - WinApi32 C 滚动条控件( slider )

c++ - "Undefined Behavior"真的允许*任何*发生吗?

r - 将嵌套 for 循环的输出存储在 r 中

c++ - 我可以在下面的代码中使用任何编译器标志来报告有关 UB 的警告吗?

c++ - 为什么我不能在 C++ 中初始化一个将自身合并到其初始值中的对象?