What is the problem with the following code snippet?

This piece of code seems to cause some compilation problems. Any explanation?

int i =20; int maxlen = i; int main() { int j = i; printf("i=%d , j=%d\n", i , j); } 
+4
source share
3 answers

In C, you cannot initialize global variables using mutable expressions. Initialization of maxlen for i is not performed, because i not a constant expression. This is part of standard C.

Why not #define constant?

 #define MAXLEN 20 
+5
source

You can use compile-time constants only when initializing a variable in this area. 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); } 
+5
source

This code is invalid in C , but valid in C ++ :

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

Error Cause -: The initialization element is not a constant

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

Work .

Because:

C ++ Standard:

3.6.1 Main function [basic.start.main]

1 The program must contain the global function main, which is the designated start of the program. The implementation determines whether the program is required in a stand-alone environment to determine the core function. [Note: in a standalone environment, startup and termination are determined by the implementation; the launch contains execution of constructors for objects of the namespace area with static storage duration; completion contains the execution of destructors for objects with static storage duration . -end note]

However, C99 says the following:

56.7.8 Initialization

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

So, not only 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
source

Source: https://habr.com/ru/post/1345261/


All Articles