C++的简单静态变量问题

C++的简单静态变量问题

问题描述:

这道题是有关局部静态变量的使用,第一次调用函数返回0,以后每次被调用返回值增加1,
但是运行结果不合乎预期,请指教!
代码如下:
#include

using namespace std;

unsigned myCnt()
{
static unsigned iCnt = -1;
++iCnt;
return iCnt;
}

int main()
{
cout << "请输入任意字符后按回车键继续" << endl;
char ch;
while (cin >> ch)
{
cout << "函数myCnt()的执行次数是:" << myCnt << endl;

}
return 0;

}
运行情况却是:
图片说明

输出的地方是不是少加了括号? myCnt()

 #include "iostream"
#include "cstdio"
using namespace std;

unsigned myCnt()
{
    static unsigned iCnt = -1;
    ++iCnt;
    return iCnt;
}
int main()
{
    cout << "请输入任意字符后按回车键继续" << endl;
    char ch;
    while (cin >> ch)
    {
        cout << "函数myCnt()的执行次数是:" << myCnt() << endl;
    }
    return 0;
}