zoukankan      html  css  js  c++  java
  • C/C++/OC 函数N个参数传递

    C/C++/OC 函数N个参数传递,使用省略号代替

    机制:函数参数是右向规则,在编译时,函数参数是从右向左写入堆栈中,从栈底低地址到栈顶高地址,如:func(int x, int y, int z); 写入顺序z -> y -> x,栈中是 x -> y -> z。

    C/C++ 实现:

     1 #include <iostream>
     2 #include <stdarg.h>
     3 
     4 /**
     5  * @brief : 函数传递N个参数
     6  * @param : ...
     7  * PS: 在参数中,必须有参数结束标志。
     8  */
     9 void func(char *first, ...);
    10 void func(char *first, ...)
    11 {
    12     va_list ap;
    13     va_start(ap, first);
    14     char *arg = NULL;
    15     while((arg = va_arg(ap, char *)) != NULL)
    16     {
    17          std::cout << "param list : " << *arg << std::endl;
    18     }
    19     
    20     va_end(va);
    21 }
    22 
    23 int main()
    24 {
    25     char *first = "first";
    26     char *second = "second";
    27     char *third = "third";
    28     // 必须以NULL为参数结束标志,在实现中就是以NULL为标志
    29     func(first, second, third, NULL);
    30 
    31     return 0;
    32 }

    PS:

    1. 引入stdarg.h头文件
    2. 获取参数方法
      1 type va_arg(va_list ap, type);
      2 void va_start(va_list ap, next_param_ptr);
      3 void va_end(va_list ap);

    OC 实现

  • 相关阅读:
    剑指offer【面试题10 :矩形覆盖】
    剑指offer【面试题3 :二维数组中的查找】
    GStreamer Tutorials
    CMake Tutorial
    python
    python
    python-线程、进程、协程
    python-类的继承
    python-操作缓存
    python-线程池
  • 原文地址:https://www.cnblogs.com/naray/p/4427397.html
Copyright © 2011-2022 走看看