简体   繁体   中英

How to have a global variable in C that increments when used by any function

I am attempting to have a gobal counter the can can used by any function in the program. Is this possible?

int* count;

main(){
   *count = 0;
}

void incrementCount(){
   ++*count;
}

int getCount(){
   return *count;
}

If not possible how can I do something similar?

No need to take a pointer. Take a Variable like

int count;

If you are going to use it in a single file better to declare it static .

A much better approach would be using the getter and setter functions instead of updating global variable everywhere

I am attempting to have a gobal counter the can can used by any function in the program. Is this possible?

Yes, even though it's not a good thing to use global variable.

All you need to do is to declare the function in global scope. You should also initialise it in main before any function call.

int count;

int main()
{
    count = 0;
    incrementCount();
    ...
}

There is no need to use pointer in your case. And it's wrong as well, because you have not allocate any memory for that pointer.

Firstly there are few issues in the shared code sample. Here

int* count; /* count is pointer i.e you need to make count to hold or point to some valid memory location */

count is of int pointer type. And here

 *count = 0; /* de-referencing uninitiated pointer */

you are trying to de-reference count which has not valid memory. It causes segmentation fault. Before de-referencing you need to allocate memory. for eg

 count = malloc(sizeof(*count));
 /* error handling of malloc return value */
 *count = 0;

I am attempting to have a gobal counter the can can used by any function in the program ?

You can do the same task without using pointer, try using static if use having file scope. If possible avoid using global variable.

You can just declare the variable as integer (not pointer).
You can have a global getter and setter function. Also initialize the global variable before any function call, best will be in Main() .

first, you can't do

*count = 0;

if you don't have initialised your pointer, it means refrenced to a variable like:

count = &x;

Then, if you want that variable is shared and the value is always updated between methods you can simply declare the variable as "static",

#include <stdio.h>
static int count;

    main(){
       printf("%d",count);
    }

    void incrementCount(){
       ++count;
    }

    int getCount(){
       return count;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM