函数和参数给出错误

Pra*_*khi 0 c printf

下面这个代码的结果应该是30,但是在编译和运行时,这给了我以下结果

the result of 2358968 and 0 is 4200271, a , b , result
Run Code Online (Sandbox Code Playgroud)

我不明白,当我没有那个值的变量时,结果怎么样?

#include<stdio.h>
#include<conio.h>

void add( int , int );   

int main(){
    add(10,20);
    getch();
    return 0 ;
}


void add(int a, int b){
    int result = a + b;
    printf("the result of the %d and %d is %d, a, b, result");  
}
Run Code Online (Sandbox Code Playgroud)

Sou*_*osh 6

在你的代码中,

printf("the result of the %d and %d is %d, a, b, result");
Run Code Online (Sandbox Code Playgroud)

应该

 printf("the result of the %d and %d is %d\n", a, b, result);
                                           ^
                                           |
                                     //format string ends here
    // arguments for format specifiers are meant to be 
   // supplied as different arguments to `printf()`, not as a part of <format> string itself
Run Code Online (Sandbox Code Playgroud)

手册页printf()

int printf(const char*format,...);

printf()家庭中的功能根据format...... 产生输出.

所以基本上你的代码应该是

 printf("<format>", var1, var2,....);
Run Code Online (Sandbox Code Playgroud)

提供的变量属于format.

代码中的问题是缺少所提供的格式说明符的变量(参数).按照C11标准,第7.21.6.1章第2段

[...]如果格式的参数不足,则行为未定义.[...]

因此,您的代码会产生未定义的行为,从而打印出一些垃圾值.

故事的道德:如果您启用了编译器警告,编译器应警告您遗漏(错配)agruments printf().因此,始终启用警告.