C中带有const变量的数组大小 [英] Array size with const variable in C

查看:465
本文介绍了C中带有const变量的数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了一个有趣的事实,但我不知道它是如何工作的.
以下代码很完美.

I've found an interesting fact, and I didn't understand how is it works.
The following piece of code just works perfectly.

#include <stdio.h>
 int main(){
  const int size = 10;
  int sampleArray[size];
  typedef char String [size];
  return 0;
}

然后,我尝试仅使用具有全局范围的常量,并且仍然可以.

Then, I tried to use only and only the constant variable with a global scope, and it's still fine.

#include <stdio.h>
const int size = 10;
 int main(){
  int sampleArray[size];
  typedef char String [size];
  return 0;
}


但是,如果我也将数组的作用域更改为全局范围,则会得到以下信息:


But, if I change the arrays's scope to global as well, I got the following:

错误:在文件范围内可变地修改了"sampleArray"

error: variably modified ‘sampleArray’ at file scope

#include <stdio.h>
const int size = 10;
int sampleArray[size];
typedef char String [size];
 int main(){
  return 0;
}

我没听懂!如果我将const变量替换为ex.到#define也可以.
我知道#define变量已经过预处理,据我所知const变量只是只读的.但是究竟是什么使全球范围扩大呢?

And I didn't get it! If I'd replace the const variable for ex. to #define it'd be okay as well.
I know that the #define variable is preprocessed, and as far as I know the const variable is only read-only. But what does make the global scope after all?

如果第二段代码没问题,我不理解第三段代码有什么问题.

I don't understand what is the problem with the third piece of code, if the second one is just okay.

推荐答案

可变长度数组可能只有自动存储时间. VLA是在C99中引入的.

Variable Length Arrays may have only automatic storage duration. VLAs were introduced in C99.

不允许使用静态存储持续时间声明VLA,因为VLA的大小在运行时确定(请参见下文)

It is not allowed to declare a VLA with the static storage duration because the size of VLA is determinated at the run time (see below)

在使用此标准之前,您可以使用以下宏之一

Before this Standard you can use either a macro like

#define SIZE 10

//...

int a[SIZE];

或枚举之类的枚举器

enum { SIZE = 10; }

//...

int a[SIZE];

通过这种方式,您可以删除const限定词并只写

By the way you may remove the const qualifier and just write

int size = 10;

代替

const int size = 10;

(在C ++中,您必须使用const限定符,尽管在C ++中,没有VLA,只是某些编译器可以具有自己的语言扩展)

(In C++ you have to use the const qualifier though in C++ there are no VLAs except that some compilers can have their own language extensions)

请注意,VLA的sizeof运算符是在运行时而不是编译时计算的.

Take into account that the sizeof operator for VLAs is calculated at the run-time instead of the compile-time.

这篇关于C中带有const变量的数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆