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

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

问题描述

从下面的代码片段可以看出,我声明了一个 char 变量和一个 int 变量.编译代码时,必须识别变量stri的数据类型.

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

推荐答案

因为像 scanfprintf 这样的可变参数函数没有可移植的方法来知道变量参数,甚至不传递多少个参数.

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(ISO/IEC 9899:201x) §7.16 变量参数) 扮演这个特殊角色,并将被传递给宏 va_start.换句话说,你不能在标准 C 中拥有这样一个原型的函数:

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天全站免登陆