2013-07-01 72 views
2

我有一个变量,我想在程序运行之前在运行时进行初始化。初始化后,我不希望变量的值改变。有没有任何C语言构造去做这件事?需要在运行时初始化的预期常量变量

让我的主C程序被包含在一个文件prog.c中

//Contents of Prog.c 
//...includes.. and variable initialization 

int main(..) 
{ 
    //Initialize variables here 
    //.. Huge program after this where I don't want these constants to change 
} 

回答

2

可以间接地做到这一点通过const指针,至少:

typedef struct { 
    int answer; 
} state; 

const state * state_init(void) 
{ 
    static state st; 

    st.answer = 42; /* Pretend this has to be done at run-time. */ 

    return &st; 
} 

int main(void) 
{ 
    const state *st = state_init(); 
    printf("the answer is %d, and it's constant\n"," st->answer); 
} 

这样,所有main()已经是一个const指向它不能修改的某个state

0

我能想到的唯一方法是,如果您将您的值作为非常量读取,然后调用一个采用常量值并将变量传递给它的函数。在功能内部,您可以完成所有希望的操作。

2

一个不断变化的全球应该工作,是吗?

const int const* g_pVal; 

int main(void) 
{ 
    static const int val = initialize_value(); 

    g_pVal = &val; 

    printf("%d\n", *g_pVal); 
} 
+0

如果变量需要从访问:

const int val = 3; // Set before main starts // const, so it will never change. int main(void) { printf("%d\n", val); // using val in code } 

然而,如果该值在编译时知道的,您可以在运行时将它设定其他功能在其他文件? –

+1

然后,你必须传递一个指针。 – Jite

+0

'* g_pVal'很容易'extern'ed,并且可以在任何链接的文件中使用。它是**全球**。 – abelenky