-23- C zero-based courses and function return parameter value, the reference variable

Function parameters

Function call, the number and type of parameters, must match the function prototype.

Shaped involved in argument

Function call, the transmission parameters, called arguments; function definition, the parameters declared in the parameter list, called a parameter.
During the function call, the argument of the transfer process, in fact, will replicate a given parameter, therefore, change the value of the parameter of the internal functions, it will not affect the caller passed for the parameter.

void FakeChangeValue(int x)
{
    x += 5;
    printf("函数内部改变数值后:%d\r\n", x);
}

void main(void)
{
    int nValue = 100;
    printf("nValue: %d\r\n", nValue);
    FakeChangeValue(nValue);
    printf("nValue: %d\r\n", nValue);
}

Another example, the following function, and no way to swap the values ​​of two variables:

void FakeSwap(int x, int y)
{
    int nTemp = y;
    y = x;
    x = nTemp;
}

Function's return value

Function uses the return statement returns using return has the connotation of two aspects:

  • The end of the current function execution and returns to the caller on the floor
  • The corresponding return value back to the caller
#include <stdio.h>


int AddTwoNumber(int x, int y)
{
    printf("返回之前的语句\r\n");
    return x + y;
    printf("返回之后的语句\r\n");
}
void main(void)
{
    int nValue = 0;
    nValue = AddTwoNumber(10, 20);
    printf("%d\r\n", nValue);
}

After the return of the return value then, should be consistent with the function prototypes for the return type void, you need only to return without return value:

#include <stdio.h>


void VoidFun()
{
    printf("返回之前的语句\r\n");
    return;
    printf("返回之后的语句\r\n");
}
void main(void)
{
    VoidFun();
}

Variadic function

Declare and implement a function, the parameter list can appear

...

It represents the number of parameters passed in the argument is not restricted.
In fact, we use the printf function is this:

In the C standard library, a va_list, va_start macro etc., see the following example, by varying the relevant parameters and macro functions, calculation and a variable number of parameters:

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

int Sum(int nFirst, ...)
{
    int nSum = 0, i = nFirst;

    va_list marker;

    va_start(marker, nFirst);
    while (i != -1)
    {
        nSum += i;
        i = va_arg(marker, int);
    }
    va_end(marker);
    return nSum;
}

void main(void)
{
    printf("求和: %d\n", Sum(2, 3, 4, -1));
    printf("求和: %d\n", Sum(5, 7, 9, 11, -1));
    printf("求和: %d\n", Sum(-1));
}

Use va_ series Macro know:

  • There must be at least a parameter
  • Va_start using a parameter initialization and
  • Use va_arg win an argument
  • Use va_end deinitialization
  • Either the caller using the convention well as the end flag parameter, or number of arguments passed in advance

Guess you like

Origin www.cnblogs.com/shellmad/p/11646264.html