0

may i declare an array with a global element in C?
Can i declare with a const type? It runs on Xcode, however I fear it isn't correct, because glob is not a const type (same thought on static type).

#include <stdio.h> #include <stdilib.h> int glob; void main (){ int const con; static int stat; int arr[glob]; int arr2[con]; int arr3[stat]; } 

In addition, I'm in need of practicing finding mistakes in C code and correcting them for a test (CS student) and could not find a resource for it.

thank you in advance.

4
  • 1
    int const con; is useless, as the variable(!) is not initialised. C does not have symbolic constants like C++ or Pascal. They are all different languages. And writing const after the type is an obsolescence feature; write const int i = ...; instead. Commented Feb 22, 2016 at 22:16
  • Just to make clear: if you expect the array to resize when the variables change, you are wrong. Commented Feb 22, 2016 at 22:32
  • I've changed my mind. This is the real duplicate: stackoverflow.com/q/18848537/3745896 Commented Feb 22, 2016 at 22:38
  • 1
    int glob; ...int arr[glob] is invalid ref as glob is 0. Commented Feb 22, 2016 at 22:41

2 Answers 2

0

Globals and statics are automatically initialized to 0 if an initializer isn't provided. The variable con local to main however isn't, so its value is undefined.

Sign up to request clarification or add additional context in comments.

22 Comments

there is another problem here. You can't declare arrays of size zero. But this is not the question.
@River - int const con;, does it not?
Actually con is uninitialised, resulting in UB. Even worse, it cannot get a value assigned. stat is not.
@River - Oh jeez, brain fart. Fixed.
@Michi: Because he fell into the same trap as I did? And because he did not really answer the actual question.
|
0

may i declare an array with a global element in C?

With C99 and optionally in C11, variable length arrays (VLA) are supported.
Array length must be more than 0.

int glob; void main (){ int arr[glob]; // bad array length 0 int arrX[glob+1]; // OK array length > 0 

Can i declare with a const type?

With VLA, yes, it is irrelevant if the type of the array size is const or not.

// Assume VLAs are allowed int a[5]; // OK 5 is a constant const int b = 4; int c[b]; // OK int d = 7; int e[d]; // OK 

With non-VLA, the array size must be a constant. A variable, const or not, is no good.

// Assume VLAs not allowed int a[5]; // OK 5 is a constant const int b = 4; int c[b]; // No good, b is not a constant. 

In addition, I'm in need of practicing finding mistakes in C code and correcting them for a test

Enable all warnings of your compiler is step 1.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.