well here is something interesting:
How many calculations, math, movements, assignments, can I do in the glbal area?
EX:

``````Header/using blah
int vap = 7;
int pav =2;
int sasd = 0;
(sasd=(vap*pav));``````

Would the last line work? Or do I have to declare a vareable to do any math/calculations?
Does it execute in a top down fashion? Or would I have to declare a function to execute that last line?

## All 3 Replies

Why don't you try it yourself? As the name of itself says "Global variables", you can only create variables, as many as your computer can.

Would the last line work?

No.

Or would I have to declare a function to execute that last line?

Yes. However, note that you can initialize sasd to that expression in the global scope:

``````int vap = 7;
int pav = 2;
int sasd = vap * pav;``````

>> Would the last line work?

No.

>> Or do I have to declare a vareable to do any math/calculations?

Yes, you can do computations to obtain the initialization value of a global variable, but you cannot do general statements.

>> Does it execute in a top down fashion?

Yes, but not really, at least, you shouldn't depend on it, it could be a subtle way to crash your program. Read this.

>> Or would I have to declare a function to execute that last line?

Yes and no. If you do as Narue suggested, then you don't need a function to execute that code at the initialization of sasd. However, any other more general set of statements (e.g. an algorithm of some kind) would require a function. But note that this function can be called in order to initialize one of the global variables, for example, you can do:

``````int var = 6;
int exponent = 4;

inline
int compute_var_exponent() {
int result = 1;
for(int i = 0; i < exponent; ++i)
result *= var;
return result;
};

int var_pow = compute_var_exponent();``````

On a final note, global variables are not recommended for anything beyond a simple test program, and experts generally only make use of them in very specific cases (often implemented as a Singleton). One of the reason they are generally undesirable is that they introduce a global state to the program which is hard to predict both at initialization (before main()) and during the execution. So, don't try to use global variables to do too much, because that's a very bad habit to have.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.