ios - xcode LLMV 3.1 编译器数组问题

标签 ios xcode compiler-construction

<分区>

我在 Apple LLVM 编译器 3.1 上遇到了以下问题:

int numIndex = 0;
int *indices = (int *)malloc(3 * sizeof(int));
indices[numIndex] = numIndex++;
indices[numIndex] = numIndex++;
indices[numIndex] = numIndex++;
for (int i = 0; i < 3; i++) {
    NSLog(@"%d", indices[i]);
}

输出: 1 0 1

int numIndex = 0;
int indices[3];
indices[numIndex] = numIndex++;
indices[numIndex] = numIndex++;
indices[numIndex] = numIndex++;
for (int i = 0; i < 3; i++) {
    NSLog(@"%d", indices[i]);
}

输出: 0 0 1

我期待 0 1 2 作为输出。使用 LLVM GCC 4.2 的相同代码会产生正确的输出。是否有任何我遗漏的优化标志或我误解的东西?

最佳答案

所以看起来行为如下

int numIndex = 0;
int indices[3];
indices[numIndex] = numIndex++;

这里首先计算右侧,返回 0,并将 numIndex 递增 1,然后计算右侧,因此 indices[1] 得到 0

indices[numIndex] = numIndex++;

这里首先计算右侧,返回 1,并将 numIndex 递增 1,然后计算右侧,因此 indices[2] 得到 1

indices[numIndex] = numIndex++;

这里首先计算右侧,返回 2,并将 numIndex 递增 1,然后计算右侧,因此 indices[3] 得到 2(实际上您超出了范围)

注意你从来没有真正分配索引[0],所以它可以是任何东西(在我的测试中它是最大整数)

编辑- 从评论看来,这实际上是未定义的行为,所以即使我观察到这一点,它也不是一个明确的答案

关于ios - xcode LLMV 3.1 编译器数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11123752/

相关文章:

swift - 在 SwiftUI 中的哪里声明扩展?

gcc - 链接器声明未找到库,strace 显示它尝试访问有效路径

c - 我如何在 (GNU) C 中编写一个代理函数来连接两个不同的调用约定?

c - 了解空 main() 到程序集的翻译

ios - LLDB - 如何在不停止进程的情况下附加到进程

ios - swift : How can I fill the cell when the data is empty?

ios - 从App Delegate检查屏幕上的UIAlertViews

ios - 是否可以在输出 ".a"库的项目中包含框架?

ios - xcode 9 中的 Facebook 登录按钮终止

ios - 使用 Alamofire 响应填充 TableView