Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am i not getting re-declaration error in global scope [duplicate]

Tags:

c

This code gives me no re-declaration error.

#include<stdio.h>

int i;
int i = 27;

int main()
{
    printf("%d",i);
    return 0;
}

According to me I declared and defined an uninitialised global variable with 0 as default value. And later re-declared, redefined and assigned it 27 value. I was expecting it to give a re-declaration error because both i's are in same scope(global). But I'm not getting any error why?

But below code gives me a re-declaration error as expected because of defining them in same scope.

#include<stdio.h>

int main()
{
    int i;
    int i = 27;
    printf("%d",i);
    return 0;
}
like image 647
Batman Avatar asked Apr 06 '21 18:04

Batman


2 Answers

At file scope, this:

int i;

Is a tentative definition since there is no initializer. It will be considered an external definition if no other definition appears.

When you then do this:

int i = 27;

This constitutes an external definition for i which matches the prior tentative definition.

These terms are defined in section 6.9.2 p1 and p2 of the C standard:

1 If the declaration of an identifier for an object has file scope and an initializer, the declaration is an external definition for the identifier.

2 A declaration of an identifier for an object that has file scope without an initializer, and without a storage-class specifier or with the storage-class specifier static, constitutes a tentative definition. If a translation unit contains one or more tentative definitions for an identifier, and the translation unit contains no external definition for that identifier, then the behavior is exactly as if the translation unit contains a file scope declaration of that identifier, with the composite type as of the end of the translation unit, with an initialize requal to 0.

Your second code snippet defines a variable in block scope (not file scope), then defines it again in the same scope. That constitutes a variable redefinition.

like image 147
dbush Avatar answered Nov 07 '22 03:11

dbush


In C this declaration in the file scope without an initializer

int i;

is a declaration of a variable and not its definition, So the next declaration

int i = 27;

is the definition of the variable.

You may declare a variable without its definition in a file scope several times though the declarations can be redundant.

like image 45
Vlad from Moscow Avatar answered Nov 07 '22 03:11

Vlad from Moscow