【C++】函数

C++对于返回值的类型有一定的限制:不能是数组,可以是其它任何类型——整数、浮点数、指针、甚至可以是结构和对象。

注意:c++的编译风格是将main函数写在其它函数前面。

需要原型(prototype)的原因?

首先,原型可以告诉编译器,函数的参数类型。如果程序没有提供这样的参数,原型可以让编译器捕捉到这种错误。其次,有返回值的函数在完成计算之后,会将返回值放在指定的位置上——可能是CPU寄存器,也可能是内存中。然后调用main从这个位置取值。原型会指定函数的返回值类型,因此编译器知道应检索多少字节以及如何解释他们。
原型可以保证:编译器正确处理函数返回值;编译器检查使用参数是否正确;编译器检查使用的参数类型是否正确,如果不正确则转换为正确类型。

指针作为函数参数

#include<iostream>
const int size = 8;
int sum(int*, int);

int main()
{
    int cookie[size] = { 1, 2, 3, 4, 5, 6, 7, 8 };
    std::cout << cookie << "=array address,";
    std::cout << sizeof(cookie) << "=size cookie\n";
    int s = sum(cookie, size);
    std::cout << "totoal:" << s << std::endl;
    s = sum(cookie, 3);
    std::cout << "total:" << s << std::endl;
    s = sum(cookie + 4, 4);
    std::cout << "total:" << s << std::endl;
    return 0;
}

int sum(int *arr, int n)
{
    int total = 0;
    std::cout << arr << "=arr,";
    std::cout << sizeof(arr) << "=sizeof arr\n";
    for (int i = 0; i < n; i++)
    {
        total = total + *(arr + i);
    }
    return total;
}

这里写图片描述

数组作为参数,传递的实际是数组的地址。所以和一般的值传递不同,值传递一般是对拷贝进行操作。而数组作为参数后,却是对原数组进行操作。由上例子可知,cookie和arr指向相同的地址。但sizeof cookie的值为32,而sizeof arr为4 。这是由于sizeof cookie是整个数组的长度,而sizeof arr只是指针变量的长度。这也是必须显示传递数组长度,而不能在sum中使用size arr的原因,指针本身并没有指出数组的长度。

指向函数的指针

double (*pt)(int);//pt points to a function that returns double
double *pt (int);//pt() a fuction that returns a pointer-to-double 

猜你喜欢

转载自blog.csdn.net/siyue0211/article/details/76974112