#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define lim sizeof keytab/sizeof keytab[0]
struct key
{
char* word ;
int count ;
};
struct key keytab[] =
{
{"char",0},
{"double",0},
{"enum",0},
{"float",0},
{"int",0},
{"long",0},
{"short",0},
{"signed",0},
{"struct",0},
{"union",0},
{"unsigned",0},
{"void",0}
};
int main()
{
printf("%d\n",lim);
system("%d\n",lim);
char* word = "void";
struct key *tab = keytab;
binsearch(word ,tab);
}
int binsearch(char* word,struct key* keytable)
{
printf("%d\n",lim);
system("%d\n",lim);
}
Interpretation : 按理说,两个输出结果都应该为12
define lim sizeof keytab/sizeof keytab[0] ,之所以第二个为0的原因就出在了 keytab上了。
当函数从main函数中走到binsearch函数中时,因为binsearch函数中的参数名和结构数组名同名,
所以binsearch函数用的参数keytab的作用域就会替代了之前的keytab的作用域,故而计算lim = 4/8,结果等于0.5,向0取整后,结果为0。
这是一个典型的作用域“偷梁换柱”的问题。