对于如何使函数中的变量保持其值,我一点也不困惑,以便下次再次调用该函数时,它仍然持有与上次运行该函数相同的值。我知道我可以把变量传递给函数etx。但是,我特别希望找到一种方法,在函数本身内创建一个变量,并使其保持值。
我想储存:
int count = 0;
这能用指针来做吗?
发布于 2016-01-19 07:15:30
它们被称为static
变量。
void Func()
{
static int count =0;
count++;
}
以下是一个示例:
#include <stdio.h>
int * Func()
{
static int count =-1;
count++;
return &count;
}
int main(void) {
printf("%d\n", *Func());
printf("%d\n", *Func());
printf("%d\n", *Func());
return 0;
}
输出:
0
1
2
发布于 2016-01-19 07:16:23
您需要使用static
存储类说明符,这将按您的需要工作。
void
function(void)
{
static int count; // Implicitly initialized to `0'
printf("called `%d' times", ++count);
}
在函数的上下文中,static
关键字使变量在函数调用中保留其值。有些库函数是用static
变量实现的,但这有一个问题。
理论上,带有静态变量的函数不是重入函数。如果您将该函数用于不同的用途或在不同的线程中保留该值,而且您可能不希望这样做,则具有此行为的函数的一个示例是strtok()
,如果您使用它来标记2个字符串,它将不像您所期望的那样工作。
为了解决这个问题,有一个strtok_r()
POSIX函数,它使用第三个参数来执行内部static
指针所做的工作,它在函数调用之间保持上下文,以处理正在被标记的给定字符串。
例如,检查以下代码
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void
function(void)
{
static int variable;
printf("thread: `0x%lX' -- value: `%d'\n", pthread_self(), ++variable);
sleep(1);
}
void *
call_the_function(void *data)
{
for (size_t i = 0 ; i < 10 ; ++i)
function();
return NULL;
}
int
main(void)
{
pthread_t thread;
pthread_create(&thread, NULL, call_the_function, NULL);
for (size_t i = 0 ; i < 10 ; ++i)
function();
pthread_join(thread, NULL);
return 0;
}
您将看到,无论哪个线程调用function()
,variable
的值都会保留下来,并且在每次调用function()
时都会增加。
https://stackoverflow.com/questions/34880377
复制