int x; //line 1
int x; //line 2
int main()
{
    return 0;
}

Both line 1 and line 2 declare as well as define the variable x. But the code doesn't give any linker errors. Why is it so?

Compilation fails only when I initialize x in both the lines.

int x=3;
int x=3;
int main(){
return 0;
}

I thought compilation would fail in code 1 because of multiple definition of variable x.

I'm new to programming, so please pardon any mistakes.

有帮助吗?

解决方案

It works because the definitions in my code are tentative in nature. So they are initially taken as declarations and upon failing to find any other instance of definition, they are combined into a single definition.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top