【问题标题】:How can you declare a global variable inside a function ? How do you make sure it remembers that value so you can use it in another function?如何在函数内声明全局变量?您如何确保它记住该值以便您可以在另一个函数中使用它?
【发布时间】:2023-02-20 23:14:58
【问题描述】:

我想在函数内声明一个全局变量,您可以从以下示例中看到:

int global_variable;

void function(int x, int y) {
    x = 58;
    y = 71;
    global_variable = x + y; // declare global variable inside function
}

int main(int z) {
    z = global_variable + 75;
    printf("result: %d \n", z);
}

结果是0,而我希望它是204作为xyz的总和。 如何确保在另一个函数中调用时记住全局变量?

【问题讨论】:

  • 1) main 的签名不正确,并且 2) function 从未被调用过。
  • 相关global_variable = x + y; // declare global variable inside function:这不是声明。这是一个任务。
  • xy作为参数传递给function (),然后立即为它们赋值是荒谬的。您在function() 中的“声明”根本不是声明;这是一个简单的任务。只有当您调用function() 时才会执行该分配。显示的代码应该打印75,而不是0

标签: c visual-studio


【解决方案1】:

这是恶作剧吗……如果不是我会尽快处理的。我希望这个例子更清楚你做错了什么。 您也可以在这里尝试您的代码: https://www.onlinegdb.com/online_c_compiler

int global_variable; // initialized with default -> 0
void function(int x, int y)
{
    global_variable = x + y; // add x and y to your global_variable
}

int main()
{

    function(71, 58);
    printf("result: %d 
", global_variable);
    global_variable += 75
    printf("result: %d 
", global_variable);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多