[英]what happens here: typedef int (*ptr) (void) in .h file C
[英]why typedef void (*f_ptr)(int); and typedef void (*f_ptr)(); work the same in C?
我在定義函數指針的時候不小心忘了加(int),我的程序仍然可以運行。 我想知道是否有任何情況下它不起作用。 我的代碼:
#include <stdio.h>
void f1(int var)
{
printf("this is f1 and var is: %d\n", var);
}
void f2(int var)
{
printf("this is f2 and var is: %d\n", var);
}
void f3(int var)
{
printf("this is f3 and var is: %d\n", var);
}
typedef void (*f_ptr)(int);
// pq eu poderia escrever: typedef void (*f_ptr)(); e o programa funcionaria normalmente?
typedef int n_casa;
int main()
{
f_ptr ptr[] = {f1, f2, f3};
int c = 0;
while (c < 3)
{
ptr[c](c);
++c;
}
return 0;
}
typedef void (*f_ptr)(int);
和typedef void (*f_ptr)();
在我的程序中工作。
它們是不同的。
typedef void (*f_ptr)(int)
聲明了一個函數指針,它只接受一個int
參數,不返回任何內容。
而對於typedef void (*f_ptr)()
,函數指針采用未指定數量的參數,並且不返回任何內容。
根據 SEI CERT C 編碼標准,建議在函數不接受參數時顯式指定void
。
根據我的一點匯編經驗:當您調用帶有參數的函數時,它會將參數壓入堆棧,然后執行該函數。 然后函數從棧頂讀取參數。
如果你不帶參數調用 f_ptr,你不會得到錯誤,你只會在var
得到一個垃圾值。 如果你用 100 個參數調用它,你只會得到第一個。
我認為編譯器沒有阻止你的唯一原因是它不夠聰明。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.