我有一个使用C语言的作业:这段代码是给我们的,它的想法是计算一个函数被调用多少次:
#include <stdio.h>
int call_counter; //global
void fun()
{ call_counter++;}
void main()
{
fun(); fun(); fun();
printf("function \"fun\" was called %d times",call_counter);
}
然后他们问我们以下问题:如果变量“ call_counter”不是全局变量,则应如何以及在何处声明它?
我试图将其声明为main内部的静态变量,但是即使调用该函数,该值也不会增加:
#include <stdio.h>
void fun()
{ call_counter++;}
void main()
{
static int call_counter = 0;
fun(); fun(); fun();
printf("function \"fun\" was called %d times",call_counter);
}
但是输出为0,我不知道如何调整代码来解决这个问题谢谢
您有四个选择:
static
在函数内部使用本地计数器,每次都返回它。对于选项2,您可以执行以下操作:
void foo(unsigned *count) {
(*count)++;
// do something
}
int main(void) {
unsigned count = 0;
foo(&count); foo(&count); foo(&count);
// count is now 3
}
对于选项3:
unsigned foo(void) {
static unsigned count;
count++;
// do something
return count;
}
int main(void) {
unsigned count;
foo(); foo();
count = foo();
// count is now 3
}
对于选项4:
void foo(void) {
// do something
}
int main(void) {
unsigned count = 0;
#define FOO_COUNT() do { foo(); count++; } while (0)
FOO_COUNT(); FOO_COUNT(); FOO_COUNT();
// count is now 3
}
或以其他更一般的方式:
#define FN_COUNT(fn, counter) do { (fn)(); (counter)++; } while (0)
void foo(void) {
// do something
}
int main(void) {
unsigned count = 0;
FN_COUNT(foo, count); FN_COUNT(foo, count); FN_COUNT(foo, count);
// count is now 3
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句