溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C語言中函數(shù)參數(shù)的省略號有什么用

發(fā)布時間:2021-08-27 18:15:58 來源:億速云 閱讀:252 作者:chen 欄目:編程語言

這篇文章主要講解了“C語言中函數(shù)參數(shù)的省略號有什么用”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“C語言中函數(shù)參數(shù)的省略號有什么用”吧!

C++允許定義形參個數(shù)和類型不確定的函數(shù)。例如,C語言中的標(biāo)準(zhǔn)函數(shù)printf便使用這種機(jī)制。在聲明不確定形參的函數(shù)時,形參部分可以使用省略號“…”代替?!啊备嬖V編譯器,在函數(shù)調(diào)用時不檢查形參類型是否與實參類型相同,也不檢查參數(shù)個數(shù)。

例如:

void ConnectData(int i,...)

在上面的代碼中,編譯器只檢查第一個參數(shù)是否為整型,而不對其他參數(shù)進(jìn)行檢查。

對于可變參數(shù)的函數(shù),需要進(jìn)行特殊的處理。首先需要引用 <stdarg.h> 頭文件,然后利用va_list類型和va_start、va_arg、va_end 3個宏讀取傳遞到函數(shù)中的參數(shù)值。

這幾個宏的定義如下(在 ANSI C 中):

type va_arg( va_list arg_ptr, type );
void va_end( va_list arg_ptr );
void va_start( va_list arg_ptr, prev_param );   

說明如下:
va_start 
sets arg_ptr to the first optional argument in the list of arguments passed to the function. The argument arg_ptr must have va_list type. The argument
prev_param is the name of the required parameter immediately preceding the first optional argument in the argument list. If prev_param is declared with the register storage class, the macro’s behavior is undefined. va_start must be used before va_arg is used
for the first time.
【 va_start函數(shù)將參數(shù)arg_ptr設(shè)置為可變參數(shù)列表的第一個參數(shù)。參數(shù)arg_ptr的類型必須為va_list。參數(shù)prev_param是在可變參數(shù)列表之前的那一個參數(shù)。(也就是說在
ANSI C 中,如果一個函數(shù)有可變參數(shù),那么在該可變參數(shù)前必須有一個明確定義的參數(shù),否則無法調(diào)用函數(shù) va_start ,例如函數(shù) int add(int i,...)是合法的,而函數(shù) int add(...)是不合法的。)】

va_arg 
retrieves a value of type from the location given by arg_ptr and increments arg_ptr to point to the next argument in the list, using the size of type
to determine where the next argument starts. va_arg can be used any number of times within the function to retrieve arguments from the list.
【 va_arg函數(shù)將返回 arg_ptr 所指位置的值,并將 arg_ptr 指向下一個參數(shù) 】
va_end
After all arguments have been retrieved, va_end resets the pointer to NULL. 

示例代碼:
#include<cstdarg>
#include<iostream>
using namespace std;

int add(int pre,...)  //求和函數(shù)
{
    va_list arg_ptr;

    int sum=0;
    int nArgValue;

    sum+=pre;

    va_start(arg_ptr,pre);
    do
    {
        nArgValue=va_arg(arg_ptr,int);
        sum+=nArgValue;
        
    }while(nArgValue!=0);   //自定義結(jié)束條件是輸入?yún)?shù)為0

    va_end(arg_ptr);

    return sum;
}
int main()
{
   cout<<add(1,2,3,0)<<endl;  //必須以0結(jié)尾,因為參數(shù)列表結(jié)束的判斷條件是讀到0停止
   return 0;

}

感謝各位的閱讀,以上就是“C語言中函數(shù)參數(shù)的省略號有什么用”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對C語言中函數(shù)參數(shù)的省略號有什么用這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI