簡體   English   中英

如何在C中使用全局變量以在不同的函數中使用相同的變量

[英]How to use global variables in C to use the same variable in different functions

我是c語言的新手,我試圖弄清楚如何使用全局變量。 如果我在一個函數中定義一個,則變量在另一個函數中未定義,但是如果在所有函數之外定義,則我想要全局的所有變量都未定義。 有關如何正確使用它們的任何提示?

您可以在main上方,包括以下位置定義它們:

#include <stdio.h>

int foo;
char *bar;

void changeInt(int newValue);

int main(int argc, char **argv) {
    foo = 0;
    changeInt(5);
    printf("foo is now %d\n", foo);
    return 0;
}

void changeInt(int newValue) {
    foo = newValue;
}

順便說一句,使用全局變量不是最佳實踐,尤其是在多線程中。 在某些應用程序中,它非常好,但是總有一種更正確的方法。 為了更恰當,您可以在main中聲明所需的變量,然后為修改它們的函數提供指向它的指針。

即。

void changeInt(int *toChange, int newValue);

int main(int argc, char **argv) {
    int foo = 0;
    changeInt(&foo, 5);
    printf("foo is now %d\n", foo);
    return 0;
}

void changeInt(int *toChange, int newValue) {
    *toChange = newValue; // dereference the pointer to modify the value
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM