4

Consider the following cases:

1.

extern int *a;
int *a = new int(1); //OK

2.

extern int a[];
int a[5]; //Ok

3.

extern int (*a)[];
int (*a)[5]; //error: redefinition of 'a' with a different type: 'int (*)[5]' vs 'int (*)[]'

Could you explain why 3rd case throw a compile-time error? What exact deffirent from previous two? I'm looking for a corresponding reference to the Standard.

4
  • 1
    Have you tried to do extern int (*a)[5]? There is a trick with the empty [] that sometimes are saw as another pointer, so your code maybe is interpreted as extern int (**a). Commented Sep 22, 2014 at 17:22
  • Just wondering, given a declaration extern int (*a)[];, what does your compiler give as sizeof a and sizeof *a? I have a vague feeling that at least one of these two expressions will not compile because it tries to take the size of an incompletely declared object. Commented Sep 22, 2014 at 18:49
  • But this is just what you've asked about earlier: The type of a cannot be completed. That's in the quote of your earlier question. Commented Sep 22, 2014 at 19:22
  • @dyp That is in the 3rd case I have that the first and the last declarations declare varibles of different types. Commented Sep 23, 2014 at 4:35

1 Answer 1

1

In Short: The 3rd scenario is different because, the type of the pointer variable mismatches - the extern declares a pointer to an array of ints with an unknown size(incomplete type), and the definition is for the same variable, but as a pointer to an array of 5 ints, which are different (valid) types according to the standard.

Detailed:

The first scenario is staightforward: the extern int* a only declares the existence of a variable of type int *. the second line defines the same variable.

the second scenario: I read through the standard again, and this is what it says:

The declared type of an array object might be an array of unknown size and therefore be incomplete at one point in a translation unit and complete later on; the array types at those two points (“array of unknown bound of T” and “array of N T”) are different types

I believe what this means is that the definition of the array with a subscript completes the previous declaration of the variable as an array with unknown size(no subscript) - this is what is happening in scenario 2.

the third scenario: Using the same meaning as from the standard, the array types at those two points are of different types. Hence case 3 fails, because the first and second declarations would then be declaring the same pointer variable as pointer to different types, leading to a "redefinition with different types" error

[Edited answer after re-reading the standard]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.