I am trying to understand if writing int arr[]; is valid in C++. So take for example:
int a[]; //is this valid?
extern int b[];//is this valid?
int (*ptrB)[]; //is this valid?
struct Name
{
int k[]; //is this valid?
};
void func()
{
ptrB++; //is this valid?
}
int a[10];
int b[10];
void bar()
{
ptrB = &b;//is this valid?
ptrB++; //is this valid?
}
int main()
{
int c[];//is this valid?
extern int d[]; //is this valid?
}
int c[10];
int d[10];
I have read some comments on SO stating that int p[]; is not valid C++. So I wanted to know in what situations is this valid/invalid. For that I wrote the above snippet and want to understand through this example.
Let us look at each of the cases. Note that all invalid statements/cases should be dropped off from the program(source code). They're written here only for the sake of presentation.
Here we have the statement
int a[]; //this is a definition so size must be known
This is not valid. So, this should not be present in the source code. Let us discuss the next case.
Here we have the statement:
extern int b[];//this is a declaration that is not a definition
This is valid. Here the type of b is incomplete. Also, b has external linkage.
Here we have:
int (*ptrB)[];
This is valid. We say that ptrB is a pointer to an incomplete type.
Here we have:
struct Name
{
int k[]; //NOT VALID
};
This is not valid as from cppreference:
Any of the following contexts requires type T to be complete:
- declaration of a non-static class data member of type T;
Here we have:
int (*ptrB)[];
void func()
{
ptrB++; //NOT VALID
}
This is not valid as from postfix increment's documentation:
The operand expr of a built-in postfix increment or decrement operator must be a modifiable (non-const) lvalue of non-boolean (since C++17) arithmetic type or pointer to completely-defined object type.
Here we have:
int (*ptrB)[];
int b[10];
void bar()
{
ptrB = &b;//NOT VALID IN C++11 but VALID in C++20
}
This is not valid in C++11 but valid in C++20, as from cppreference:
References and pointers to arrays of unknown bound can be formed, but cannot(
until C++20)and can(since C++20) be initialized or assigned from arrays and pointers to arrays of known bound.
Here we have:
int (*ptrB)[];
void bar()
{
ptrB++; //NOT VALID
}
This is not valid as from cppreferene:
The type of a pointer to array of unknown bound, or to a type defined by a typedef declaration to be an array of unknown bound, cannot be completed.
So we will get the same error as in case 5.
Here we have:
int main()
{
int c[];
}
This is not valid since this is a definition and so size must be known.
Here we have:
int main()
{
extern int d[]; non-defining declaration
}
This is valid. d has external linkage.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With