为什么没有这个C程序编译?有什么不对呢? [英] Why doesn't this C program compile? What is wrong with this?

查看:100
本文介绍了为什么没有这个C程序编译?有什么不对呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么没有这个C程序编译?有什么不对呢?

我已经尝试过在 wxDevC ++ 和Turbo C ++ 3.0。

MAIN.C

 #包括LT&;&stdio.h中GT;
#包括LT&;&CONIO.H GT;const int的SIZE = 5;INT主(INT ARGC,字符** argv的)
{
    字符数组[SIZE] = {'A​​','B','C','D','E'};    的printf(数组元素,\\ n);
    INT I = 0;    对于(i = 0; I<大小; ++ I)
    {
        的printf(%C,数组[我]);
    }    残培();    返回0;
}

这两个编译器的错误信息是相似的。

  F:\\ _源 -  codeS \\ main.c中在功能`主':8 F:\\ _源 -  codeS \\ main.c中可变大小的物体可能无法初始化


解决方案

在C89 / 90语言数组的大小必须由一个整体的恒前pression指定的(一般如此C99作为好)。在C A const int的的对象不是一个的恒前pression 的,这就是为什么你不能用它来指定数组大小。注:这是C和C ++之间的一个显着的区别

在C语言中词的的是指的文字的常数,即 5 10.2 0xFF的'A'等(枚举常量也常量的,是precise)。 const int的对象,再一次,不是的的C和不能用于构建恒恩pressions。

如果您想pre-声明一个命名常量被使用在C数组大小,您可以选择使用的#define 枚举。这同样适用于区分标签,位字段大小和每一个其他上下文需要恒定的前pression。

请参阅this了解更多详情。

Why doesn't this C program compile? What is wrong with this?

I have tried it on wxDevC++ and Turbo C++ 3.0.

Main.c

#include<stdio.h>
#include<conio.h>

const int SIZE = 5;

int main(int argc, char ** argv)
{    
    char array[SIZE] = {'A', 'B', 'C', 'D', 'E'};

    printf("Array elements are,\n");
    int i=0;

    for(i=0 ; i<SIZE ; ++i)
    {
        printf("%c  ", array[i]);
    }

    getch();

    return 0;
}

Error Messages on the both of the compilers are similar.

f:\_Source-Codes\main.c In function `main':

8 f:\_Source-Codes\main.c variable-sized object may not be initialized

解决方案

Array size in C89/90 language must be specified by an integral constant expression (in general true for C99 as well). A const int object in C is not a constant expression, which is why you can't use it to specify array size. Note: this is one prominent difference between C and C++.

In C language the term constant refers to literal constants, i.e. 5, 10.2, 0xFF, 'a' and so on (enum constants are also constants, to be precise). const int object, once again, is not a constant in C and cannot be used to build constant expressions.

If you want to pre-declare a named constant to be used as array size in C, you have to use either #define or enum. The same applies to case labels, bit-field sizes and every other context requiring a constant expression.

See this for more details.

这篇关于为什么没有这个C程序编译?有什么不对呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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