using info from functions to define other functions and structures

I first posted this here http://www.cplusplus.com/forum/beginner/45574/ but I think it might have been in the wrong section, and maybe I didn't explain it very well so I thought I'd rephrase it here with a bit more detail.

Say I have a function, get_global() that carries out some operations and then returns a value that I will declare as a const int MYGLOBAL. Now, I also want to define a structure called mystruct, whose members will be arrays whose lengths are defined by the MYGLOBAL. and another function called fun_build_mystruct() which will return a structure member of type mystruct. Conceptually, I would do this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include<headers.h>

const int get_global() {
    // define my function here
    return MYGLOBAL;
}

const int MYGLOBAL = get_global(); // Can't do this! - we're not in main()

struct mystruct {
    int structarray [MYGLOBAL] // this array size is dependant on the value returned by get_global()
};

mystruct * fun_build_mystruct() {
    mystruct MEMBER;
    return MEMBER;
}

main () {
    //do stuff
    return 0;
}


This however, doesn't work because I can't call get_global() outside of main(). But I can't define my functions inside main, and I can't even declare prototypes because fun_build_mystruct() needs mystruct to be defined before it can be declared. How is this sort of thing normally handled??
closed account (zb0S216C)
1) on line 5, MYGLOBAL is undefined at that point.

2) Line 8 is valid in VCE2010.

3) Line 11 generates an error.

4) On line 16, you return a local instance of mystruct. Don't do this. Still, you don't use the address of operator on MEMBER on line 16.

5) main( ) should be given a return type.


Wazzak
Last edited on
A constant is something you should know at compile time. If you have to call a function to decide its value at run time, use a normal integer and dynamic memory.

Though, as Framework said,
1
2
3
4
5
int f(){
   return 5;
}

const int i = f();
works fine on VC++..
Last edited on
Topic archived. No new replies allowed.