百科问答小站 logo
百科问答小站 font logo



C语言中按%d打印char会不会把相邻内存的也print出来? 第1页

  

user avatar   gou-rou-hua-yu-guo 网友的相关建议: 
      

不会,因为C标准是这么规定的

6.5.2.2:6
If the expression that denotes the called function has a type that does not include a
prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions. .......
— one promoted type is a signed integer type, the other promoted type is the corresponding unsigned integer type, and the value is representable in both types;
— both types are pointers to qualified or unqualified versions of a character type or void


6.5.2.2:7
If the expression that denotes the called function has a type that does include a prototype, the arguments are implicitly converted, as if by assignment, to the types of the corresponding parameters, taking the type of each parameter to be the unqualified version of its declared type. The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.

简单说呢,根据6.5.2.2:7 可变参数要做default argument promotions

那么什么叫default argument promotions呢?在6.5.2.2:6里规定了,整型做integer promotions, float则转换至double就叫default argument promotions

至于什么叫integer promotions呢?

6.3.1.1:2
If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.

简单说,如果int存得下,那就转换成int,否则转换成unsigned int,这叫integer promotions

所以答案是,变参里的char类型参数会被转换成int类型


PS:

这里顺便纠正一个广为流传的关于printf格式控制符的错误:

很多人提到printf用法时,都会说%f打印的float,%lf打印double,这是错误的

根据上面提到的C标准,我们可以知道变参里的float类型变量会被转换成double类型变量,因此printf不可能接收float类型的变量, %f打印的是double




  

相关话题

  为什么有些编程语言写完一句后要加分号? 
  像C语言这样的编译型语言能否在不同CPU上,通过相同标准库的编译器,用源代码实现跨平台? 
  为什么大多数程序主函数成功时都return 0; 不return 1; ? 
  同样用pow()表示10^2,为什么分别用字面量和变量作参数会返回不同的值? 
  如果鸿蒙系统成功,会复兴C/C++吗? 
  请问#define PI 3.1416比float pi=3.1416有什么优势呢? 
  如果使 1÷0 有意义,那么应该等于多少? 
  《C专家编程》第六十页参数在传递时为什么会首先放到寄存器中? 
  大型项目中面向过程思想 vs 面向对象思想,哪种开发效率更高? 
  c语言程序经过编译后,每条指令都有一个内存地址,那两个程序如果有相同内存地址的指令怎么办? 

前一个讨论
为什么仙剑奇侠传电视剧十几年间争议不断?
下一个讨论
Python中for i in somelist,如果在for循环内改变somelist会发生什么?





© 2024-12-22 - tinynew.org. All Rights Reserved.
© 2024-12-22 - tinynew.org. 保留所有权利