为什么此代码的行为在 C 中未定义? [英] Why is the behaviour of this code undefined in C?

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

问题描述

我收到了这段代码,但我不太确定为什么它的行为是未定义的.我的猜测是它与两个字符串的内存位置以及 if 条件中的位置比较有关.

I've been given this code and I'm not quite sure why its behaviour is undefined. My guess is that it has something to do with the memory locations of the two strings and the location(s)' comparison in the if condition.

int main(void) { 
  char *str1 = "xyz"; 
  char *str2 = "xyz";

  if (str1 == str2) {
     printf("Same!\n");
  }  else {
     printf("Not Same!\n");
  }
  return 0; 
}

推荐答案

关于是否折叠相同的字符串常量以占用相同的内存,这是未指定的(不是未定义,有一个微妙的区别).

It's unspecified (not undefined, there's a subtle distinction) as to whether identical string constants are folded to occupy the same memory.

C++11, 6.4.5 字符串文字/6 声明:

未指定这些数组是否不同,前提是它们的元素具有适当的值.如果程序试图修改这样的数组,行为是未定义.

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

str1str2 都是指向包含四个字符 { 'x', 'y', 'z', '\ 的内存块的指针0'} 并且根据定义,它们是不可修改的.

Both str1 and str2 are pointers to a block of memory containing the four characters { 'x', 'y', 'z', '\0'} and they are, by definition, non-modifiable.

这意味着编译器可以自由地将这两个变量设置为指向相同内存块,以提高效率,如果它愿意的话.

That means the compiler is free to set both those variables to point to the same block of memory, for efficiency, if it so desires.

因此 str1str2(我说的是指针,显然指针后面的内容是相同的)可能相同或不是.

Hence str1 and str2 (I'm talking about the pointers, obviously the content behind the pointers is identical) may be identical or not.

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

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