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.

John
  • 11

2 Answers2

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.

BingsF
  • 1,269
  • 10
  • 15
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.

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256