gpt4 book ai didi

c++ - int arr[ ] 是有效的 C++ 吗?

转载 作者:行者123 更新时间:2023-12-05 08:36:06 25 4
gpt4 key购买 nike

我想了解编写 int arr[]; 在 C++ 中是否有效。举个例子:

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];

我读过一些关于 SO 的评论,指出 int p[]; 不是有效的 C++。所以我想知道在什么情况下这个有效/无效。为此,我写了上面的代码片段,并想通过这个例子来理解。

最佳答案

让我们看看每个案例。

案例一

这里有语句

int a[]; //this is a definition so size must be known

无效

案例2

这里有语句:

extern int b[];//this is a declaration that is not a definition

这是有效。这里 b 的类型是不完整。此外,b 具有外部链接

案例三

这里有:

int (*ptrB)[]; 

这是有效。我们说 ptrB 是一个指向不完整类型的指针

案例4

这里有:

struct Name
{
int k[]; //NOT VALID
};

cppreference 开始无效 :

Any of the following contexts requires type T to be complete:

  • declaration of a non-static class data member of type T;

案例5

这里有:

void func()
{
ptrB++; //NOT VALID
}

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.

案例6

这里有:

void bar()
{
ptrB = &b;//NOT VALID
}

cppreference 开始无效 :

The declared type of an array object might be an array of unknown bound 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.

案例7

这里有:

void bar()
{
ptrB++; //NOT VALID

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.

所以我们会得到与情况 5 相同的错误。

案例8

这里有:

int main()
{
int c[];
}

这是无效,因为这是一个定义,所以大小必须已知。

案例9

这里有:

int main()
{
extern int d[]; non-defining declaration
}

这是有效d 具有外部链接

关于c++ - int arr[ ] 是有效的 C++ 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70631288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com