Learn point C language (40): function

Source: Internet
Author: User
Tags integer printf

Like printf, this multimodal function is borrowed from the macros in Stdarg.h.

va_list : 用于定义遍历参数列表的指针;
va_start : 让指针指向第一个参数;
va_arg  : 获取下一个参数,并向后移动一个位置;
va_end  : 释放指针,完成遍历.

1. Integer sum:

This example implements a summation of a series of integers, requiring at least three parameters and the last one must be 0.

The last 0 is used to identify the end of the list.

#include <stdio.h>
#include <stdarg.h>

int sum(int n1,int n2,...)
{
  /* 定义一个指向参数列表的指针,必须是 va_list 类型 */
  va_list p;

  /* 定义输出变量,并先获取前两个值 */
  int out = n1 + n2;

  /* 把指针指向最后一个明确的变量 */
  va_start(p,n2);

  /* 用 va_arg 获取下一个整数值,va_arg 会同时把指针向后移动整数大小的位置 */
  /* 本例是假定参数都是整数值,遇 0 终止; 这样在使用是最后一个参数必须是 0 */
  while ((n2 = va_arg(p,int)) != 0) out += n2;

  /* 结束 */
  va_end(p);

  return(out);
}

int main(void)
{
  printf("%d\n",sum(2,2,2,0));       /* 6 */
  printf("%d\n",sum(1,2,3,4,5,6,7,8,9,0)); /* 45 */
  getchar();
  return 0;
}

2. Integer summation (modified version):

This function requires at least two parameters, and finally must be 0.

#include <stdio.h>
#include <stdarg.h>

int sum(int n1,...)
{
  va_list p;
  int out = n1;
  va_start(p,n1);
  while ((n1 = va_arg(p,int)) != 0) out += n1;
  va_end(p);
  return(out);
}

int main(void)
{
  printf("%d\n",sum(2,0));         /* 2 */
  printf("%d\n",sum(1,2,3,4,5,6,7,8,9,0)); /* 45 */
  getchar();
  return 0;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.