我可以'some'在MSVC生成的汇编代码中看到两个文字,但只有一个有clang和gcc.这导致完全不同的代码执行结果.
static const char *A = "some";
static const char *B = "some";
void f() {
if (A == B) {
throw "Hello, string merging!";
}
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释这些编译输出之间的差异和相似之处吗?为什么即使没有请求优化,clang/gcc也会优化某些内容?这是某种未定义的行为吗?
我还注意到,如果我将声明更改为下面显示的声明,则clang/gcc/msvc根本不会"some"在汇编代码中留下任何声明.为什么行为不同?
static const char A[] = "some";
static const char B[] = "some";
Run Code Online (Sandbox Code Playgroud) #include<stdio.h>
#include<string.h>
int main()
{
char * p = "abc";
char * p1 = "abc";
printf("%d %d", p, p1);
}
Run Code Online (Sandbox Code Playgroud)
当我打印两个指针的值时,它打印相同的地址.为什么?
我知道为了比较C中的两个字符串,您需要使用该strcmp()函数.但我试图将两个字符串与==运算符进行比较,并且它有效.我不知道如何,因为它只是比较两个字符串的地址.如果字符串不同,它应该不起作用.但后来我打印了字符串的地址:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* str1 = "First";
char* str2 = "Second";
char* str3 = "First";
printf("%p %p %p", str1, str2, str3);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
00403024 0040302A 00403024
Process returned 0 (0x0) execution time : 0.109 s
Press any key to continue.
Run Code Online (Sandbox Code Playgroud)
怎么可能str1和str3具有相同的地址?它们可能包含相同的字符串,但它们不是同一个变量.
I'd like to ask if is it portable to rely on string literal address across translation units? I.e:
A given file foo.c has a reference to a string literal "I'm a literal!", is it correct and portable to rely that in other given file, bar.c in instance, that the same string literal "I'm a literal!" will have the same memory address? Considering that each file will be translated to a individual .o file.
For better illustration, follows an …