传递的参数vs.变量声明

Arguments passing vs. Variable declaration

本文关键字:变量 声明 vs 参数      更新时间:2023-10-16

在函数定义中将参数作为参数传递到函数内部和将参数声明为函数声明块内部的变量之间有什么区别?

利用我的评论来了解问题的要点。

#include<iostream>
         int max=0;
         int t=0;
    class stack
    {
         int s[10];
    public:
         void push(int);
         void pop();
    };
    void stack::push(int y) //argument passed inside function parameter
    {
          if(t<=max);
          {
               s[t]=y;
               t=t+1;
          }
          else
          cout<<"Stack overflow";
    }
    void stack::pop()
    {
         int item; //variable declared inside function definition
         if(t>=0)
         {
               t=t-1;
               item=s[t+1];
         }
    }

一个区别是参数由调用者初始化,但局部变量必须由函数初始化。

int somefunc(int arg)
{
    int local = 0;
    …
    return local + arg;
}

调用函数时:

int x = somefunc(23);

函数中的变量CCD_ 1由调用代码用值23初始化。然而,局部变量local必须显式初始化(在本例中为= 0;如果它是类类型,则由适当的构造函数进行初始化)。未显式初始化的内置类型(如int)的局部变量会得到一个准随机值。

一个区别在于如何解释数组:

// returns nonzero iff array1 equals {1, 2, 3}
int func(int array1[], size_t size1)
{
    int array2[] = {1, 2, 3};
    return size1 == sizeof(array2) && memcmp(array1, array2, size1) == 0;
}

虽然array2是一个由3个整数组成的数组,但array1是一个未知大小的数组,这就是为什么我们通常会为大小传递第二个参数。这是因为数组在传递到像这样的函数时"衰减为指针"。你可以在这里读到:什么是数组衰减?

在C++中,使用数组大小的值模板可以处理这一问题,但上述技术也适用于C和大多数C++代码。

除了数组之外,函数参数中使用的C类型的行为与局部变量中使用的C类型几乎相同。

参数是通过调用该函数传递的。所以调用者决定应该传递什么。函数决定它应该接受什么。例如:

    main()
    {
        int i=0;
        int k=i;
        for (int j=i; j `enter code here`< n; j++)
        {
        }
    }
is same as
    main()
    {
       int i=0,k;
       
        for (int j=k=i; j < n; j++)
        {
        }
   }
 but this
   main()
    {
       int i=0,k;
       
        for (int j=i; j < n; j++)
        {
           k=i;
        }
   }
is totally different.