How to share a variable between two functions in C?

后端 未结 6 1858
抹茶落季
抹茶落季 2021-01-22 16:27

In C, suppose var1 is a variable in foo1() and foo2() wants to access var1, however, foo1() doesn\'t call foo2(), so we can\'t pass it by parameter. At the same time, only foo1(

6条回答
  •  佛祖请我去吃肉
    2021-01-22 17:14

    by reference is one way: (in this example the memory for i is local to caller())

    void caller()
    {
        int i = 5;
        foo(&i);
        bar(&i);
        printf("\n final i is %d",i);
    }
    
    void foo(int *i)
    {
        printf("%d",*i);
        *i += 5;
    }
    
    void bar (int *i)
    {
        printf("%d",*i);
        *i += 5;
    }
    

    global: (usually considered horrible i would have a name more like GLOBAL_I or something)

    int i = 0;
    
    void caller()
    {
       i=5;
       foo();
       bar();
       printf("\n final i is %d",i);
    }
    
    void foo()
    {
       printf("%d",i);
       i += 5;
    }
    
     void bar (int i)
     {
          printf("%d",i);
          i += 5;
     }
    

提交回复
热议问题