为什么每次在C中都必须为printf()和scanf()指定数据类型? [英] Why do I have to specify data type each time in C to printf() and scanf()?

查看:70
本文介绍了为什么每次在C中都必须为printf()和scanf()指定数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从下面的代码片段中可以看到,我声明了一个 char 变量和一个 int 变量.编译代码时,它必须标识变量 str i 的数据类型.

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.

为什么在扫描变量期间需要通过将%s %d 指定为 scanf ?声明变量时,编译器还不够成熟,无法识别出来吗?

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;
}

推荐答案

因为没有可移植的方式来使诸如 scanf printf 之类的变量参数函数知道可变参数,甚至没有传递多少参数.

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.

请参阅C常见问题解答:我如何发现函数实际使用了多少个参数?

See C FAQ: How can I discover how many arguments a function was actually called with?

这就是为什么必须至少有一个固定参数来确定变量参数的数量,也许是类型的原因.这个参数(标准称为 parmN ,请参见C11(

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中都必须为printf()和scanf()指定数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆