0 c variables declaration definition
变量/函数可以声明多次,但只能定义一次。这实际上是什么意思?
我试图了解有关在线编译器的声明,但我期望显示错误,但事实并非如此。
#include <stdio.h>
int x=10;
int main() {
x=20;
x=30;
printf("%d",x);
}
Run Code Online (Sandbox Code Playgroud)
预期的输出:因为我已经定义了变量x并分配了三个不同的值10、20、30,所以我希望显示错误。这个概念说您可以声明变量多次,但只能定义一次,因为不能将两个不同的位置赋给同一变量实际输出:30
x = 10;不是定义。这是一项任务。您可以分配任意多次。
int x;是一个定义(同时也是一个声明)。同样,extern int x;是一个声明(没有定义)。为了说明您所询问的概念,以下是有效的C:
// Duplicate declaration: OK
extern int x;
extern int x;
// Definition: OK
int x;
// int x; // Duplicate definition: ERROR
// Definition with initialisation: OK
int y = 42;
// (Re)assignment: OK inside function.
x = 1;
y = 2;
Run Code Online (Sandbox Code Playgroud)
对于函数,语法是不同的。要声明一个函数,请编写其原型。要定义它,请添加一个函数主体:
// Declaration:
int f(void);
// Also possible, but unnecessary:
extern int f(void);
// Definition:
int f(void) { return 42; }
Run Code Online (Sandbox Code Playgroud)