Gianni Gentile Gianni Gentile - 14 days ago 6
C Question

How to make a "global variable" with a table?

In my program, I need to use a "global variable" which is D[M] (where M is a constant defined in the preprocessor directives)

The problem is that in the function I have in the program, the prototype isn't using D[M] (while the function is using it)

So I thought "If they call it a global variable, it means that the table is a constant, right ?" but I can't find a way to make a constant (#define) with a table (#define D[M] or #define D[])

Do you guys know what did they (my professor) meant by saying "The program use a global variable D, which is a table of M integers" ?

Here's my program if it can help (it's mostly french but i think it's understandable) :

http://pastebin.com/0WfRxa3e

(The purpose of this program is to find wether or not ' n ' (or ' u ' in the function) is a prime number + if it's a perfect number)
It's not finished yet as I wanted to check if the "while" condition worked as I wanted to..

Thanks a lot !

Answer

The program use a global variable D, which is a table of M integers.

This is probably what is meant:

#define M 10
int D[M] = {0};
int main() {
  D[0] = 42; // can access array here, because it's a global variable
  return 0;
}

If they call it a global variable, it means that the table is a constant, right?

Global variables are not necessarily constant (read-only). Note that preprocessor macros (#define ...) and constants (static const int ...) are not quite the same thing.

For further reading:

Comments