![](/img/trans.png)
[英]How can I reduce the number of arguments with this "printf" function? Should I be using something other than "printf"?
[英]How can the compiler able to warn if I pass more arguments to printf function?
一般來說,當使用可變參數函數時,我們總是給出一些預期輸入的數量,但永遠不知道傳遞了多少。
那么,當我傳遞的 arguments 多於printf()
function 所需的數量時,編譯器如何檢測到?
下面是示例代碼
#include <stdio.h>
int main()
{
printf("Hello World", 2);
return 0;
}
Output:
main.c: In function ‘main’:
main.c:6:12: warning: too many arguments for format [-Wformat-extra-args]
6 | printf("Hello World", 2,3,4);
| ^~~~~~~~~~~~~
Hello World
我使用的是以下在線編譯器: https://www.onlinegdb.com/online_c_compiler
使用的編譯器足夠聰明 (*) 可以將printf()
識別為特殊的 function,在本例中為標准庫的 function。 這個 function 接收格式字符串。 如果編譯器可以讀取此格式字符串,它會像printf()
那樣解釋格式代碼。 因此它期望以下 arguments 的數量和類型。
您可以將此功能用於您自己的類似 printf 的 function,例如(無恥地從GCC 的手冊中復制):
extern int
my_printf (void *my_object, const char *my_format, ...)
__attribute__ ((format (printf, 2, 3)));
(*) “足夠聰明”意味着printf()
在“stdio.h”中聲明了這個屬性,編譯器知道如何處理這個屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.