以下代码:
#include<stdio.h>
#include<stdlib.h>
char *msg = "Hello, World!";
char *p;
p = msg;
int main()
{
puts(msg);
return EXIT_SUCCESS;
}
给出错误:错误C2040:'p':'int'与'char *'的间接级别不同
但是当我们在 main 中更改指针赋值 p = msg 时没有错误吗?
#include<stdio.h>
#include<stdlib.h>
char *msg = "Hello, World!";
char *p;
int main()
{
p = msg;
puts(msg);
return EXIT_SUCCESS;
}
有什么建议吗?
在 C 中,所有在主函数之外声明的变量都会被初始化
@compile-time
,因此,所有这些变量都必须通过静态赋值来初始化。
例如:
#include<...>
int a = 5; // constant initialization
char* str = "HELLO WORLD"; // constant initialization
int b; // declared but uninitialized
b = a; // ILLEGAL: this is not an initialization, so it can't be solved @compile-time
int c = a; // ILLEGAL: dynamic init: depends on a value(a), so it can't be solved @compile-time
int main(){
...
return 0;
}
所有不正确静态常量初始化的操作都必须在主函数内完成,这是唯一启动的程序
@run-time
。
相反,如果您想提供一些预处理控制,您可以使用 #define
指令,这些指令是编译器的指令,只是为了提高代码可读性并避免直接处理值:
#include<stdio.h>
#include<stdlib.h>
#define MSG = "HELLO WORLD"
char* msg = MSG; // constant initialization with MSG macro
char* p; // constant initialization with MSG macro
int main(){
puts(msg);
return EXIT_SUCCESS;
}