C語言中fun1()和fun2(void)的區別
在一次C語言實訓中我發現老師在對無參函式的書寫中寫成fun2(void)的形式,這引起了我的好奇心,我只知道fun1()和fun2(void)是兩個無參函式,后者是C99中規定的,void的意思就是該函式不接受任何引數,但是我在使用的程序中除了對fun2傳參會導致報錯以外沒有發現別的問題,所以就開始好奇為什么老師在實訓時會特意在沒有傳參的函式里寫上void,
經過谷歌搜索得到以下結論
(C) The difference between int main() and int main(void)
A common misconception for C programmers, is to assume that a function prototyped as follows takes no arguments:
int foo();
In fact, this function is deemed to take an unknown number of arguments. Using the keyword void within the brackets is the correct way to tell the compiler that the function takes NO arguments.
參考文章:https://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044841143&id=1043284376
但是我還是不能理解到底為什么要這樣定義,最后在抖音的一個博主(抖抖代碼)那里得到了解答
以下是博主演示的代碼:
#include<stdio.h>
int main(void){
void fun1();
void fun2(void);
fun1();
fun2();
return 0;
}
void fun1(){
printf("doudou \n");
}
void fun2(){
printf("douodu 2\n");
}
/*
得到輸出為:
doudou
douodu 2
*/
在沒有傳入任何引數的情況下兩者都是被正常運行的,
但是如果對fun1和fun2分別進行傳參,其結果如下
//fun1
#include<stdio.h>
int main(void){
void fun1();
void fun2(void);
fun1(888,999);
// fun2();
return 0;
}
void fun1(){
printf("doudou \n");
}
void fun2(){
printf("douodu 2\n");
}
//輸出為
//doudou
#include<stdio.h>
int main(void){
void fun1();
void fun2(void);
// fun1(888,999);
fun2(888,999);
return 0;
}
void fun1(){
printf("doudou \n");
}
void fun2(){
printf("douodu 2\n");
}
/*輸出為
test.c:20:5: error: too many arguments to function 'fun2'
fun2(888,999);
^~~~
test.c:18:10: note: declared here
void fun2(void);
*/
由此得出,在對fun1()和fun2(void)傳參時,fun2會直接報錯中斷程式的運行,如果不含參的函式不帶void并進行傳參的話,表面上不會有任何影響,但是在Linux或者Unix平臺中函式的引數會被推入堆疊中,所以只要讀取引數所推入的暫存器便可獲得傳入的引數
#include <stdio.h>
int main(void)
{
void fun1();
fun1(888, 999);
return 0;
}
void fun1()
{
register int sp1 asm("di"); //關聯第一個引數
register int sp2 asm("si"); //關聯第二個引數
printf("%d,%d", sp1, sp2);
}


研究這個問題花費了我三個小時,三個小時的時間也許可以讓我學完一種特性或者幾個語法糖,但是對這個小細節的求解卻讓我樂在其中,編程的魅力讓我無法自拔,
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/265960.html
標籤:其他
