phoenix
phoenix

Reputation: 559

What is the problem with the following piece of code?

This piece of code seems 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);
}

Upvotes: 4

Views: 332

Answers (3)

Sadique
Sadique

Reputation: 22821

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.

Upvotes: 0

Paul Sasik
Paul Sasik

Reputation: 81459

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);
}

Upvotes: 5

Rafe Kettler
Rafe Kettler

Reputation: 76955

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

Upvotes: 5

Related Questions