为什么我在C每次指定数据类型? [英] Why do I have to specify data type each time in C?
问题描述
你可以从下面的code段看,我已经宣布有一个字符
变量和一个 INT
变量。当code被编译,就必须确定变量的数据类型 STR
和 I
。
为什么我需要扫描我的变量,它是一个字符串或整数变量时再告诉指定%S
或%d个
为 scanf函数
?是不是编译器足够成熟来确定,当我宣布我的变量?
的#include<&stdio.h中GT;诠释的main()
{
焦炭海峡[80];
INT I; 的printf(请输入您的姓氏:);
scanf函数(%S,STR);
的printf(请输入您的年龄:);
scanf函数(%d个,&安培; I) 返回0;
}
由于有一个可变参数的功能,如 scanf函数
和的printf没有可移植的方法
来知道类型的变量参数,很多参数甚至没有传递方式。
详见C常见问题解答:我怎样才能找到一个函数有多少实际的参数调用
此的原因是,必须有至少一个固定的参数,以确定的可变参数的数目,以及也许的种类,。而这个参数(标准称之为 parmN
,见C11(的ISO/IEC 9899:201X )§7.16的可变参数的),这起特殊作用,并且将被传递给宏的va_start
。换句话说,你不能有一个函数原型像这样标准C:
无效美孚(...);
As you can see from the code snippet below, I have declared one char
variable and one int
variable. When the code gets compiled, it must identify the data types of variables str
and i
.
Why do I need to tell again during scanning my variable that it's a string or integer variable by specifying %s
or %d
to scanf
? Isn't the compiler mature enough to identify that when I declared my variables?
#include <stdio.h>
int main ()
{
char str [80];
int i;
printf ("Enter your family name: ");
scanf ("%s",str);
printf ("Enter your age: ");
scanf ("%d",&i);
return 0;
}
Because there's no portable way for a variable argument functions like scanf
and printf
to know the types of the variable arguments, not even how many arguments are passed.
See C FAQ: How can I discover how many arguments a function was actually called with?
This is the reason there must be at least one fixed argument to determine the number, and maybe the types, of the variable arguments. And this argument (the standard calls it parmN
, see C11(ISO/IEC 9899:201x) §7.16 Variable arguments ) plays this special role, and will be passed to the macro va_start
. In another word, you can't have a function with a prototype like this in standard C:
void foo(...);
这篇关于为什么我在C每次指定数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!