Does the confliction between declaration and definition cause undefined behavior?

  • A+
Category:Languages

For example, in one source file:

extern int a[10]; int main() {    (void)sizeof(a);    return 0; } 

and in a second source file we have:

int a[20];//different with the first source  

Does the code above cause undefined behavior? As far as I know, in C it says:

All declarations that refer to the same object or function shall have compatible type; otherwise, the behavior is undefined.

Are int[10] and int[20] compatible(in c's view)? And what about C++ standard?

Besides, if there is no second source file, is it legal to use sizeof(a) (a has just a declaration) ?

 


Yes this is undefined behavior in C, they are not compatible, see C11 6.7.6.2 Array declarators paragraph 6

For two array types to be compatible, both shall have compatible element types, and if both size specifiers are present, and are integer constant expressions, then both size specifiers shall have the same constant value. If the two array types are used in a context which requires them to be compatible, it is undefined behavior if the two size specifiers evaluate to unequal values.

and ill-formed no diagnostic required in C++ from [basic.link]p11:

After all adjustments of types (during which typedefs are replaced by their definitions), the types specified by all declarations referring to a given variable or function shall be identical, except that declarations for an array object can specify array types that differ by the presence or absence of a major array bound ([dcl.array]). A violation of this rule on type identity does not require a diagnostic.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: