开发者

What is the problem with the following piece of code?

This piece of code se开发者_运维技巧ems to be creating some troubles while compiling. Any explanation?

int i =20;
int maxlen = i;
int main()
{
     int j = i;
     printf("i=%d , j=%d\n", i , j);
}


In C, you can't initialize global variables using non-constant expressions. Initializing maxlen to i fails because i is not a constant expression. It's part of the C standard.

Why not #define a constant?

#define MAXLEN 20


You can only use compile-time constants when initializing a variable at that scope. Try:

int i = 20;
int maxlen;

int main()
{
   maxlen = i; // assign within the scope of a function
   int j = i;
   printf("i=%d , j=%d\n", i , j);
}


This Code is Invalid in C but valid in C++:

C - http://www.ideone.com/mxgMo

Error Reason -: initializer element is not constant

C++ - http://www.ideone.com/XzoeU

Works.

Because:

The C++ Standard states:

3.6.1 Main function [basic.start.main]

1 A program shall contain a global function called main, which is the designated start of the program. It is implementation defined whether a program in a freestanding environment is required to define a main function. [ Note: in a freestanding environment, start-up and termination is implementation-defined; start-up contains the execution of constructors for objects of namespace scope with static storage duration; termination contains the execution of destructors for objects with static storage duration. —end note ]

However, C99 says this:

56.7.8 Initialization

4 All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

So not just the code you posted, but something like this will also be invalid in C:

#include<stdio.h>

int needint(void);

int i =needint();

int needint(void)
{
    return 1;
}

int main()
{
   int j = i;
   printf("i=%d , j=%d\n", i , j);
}

See here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜