传递的参数vs.变量声明
Arguments passing vs. Variable declaration
在函数定义中将参数作为参数传递到函数内部和将参数声明为函数声明块内部的变量之间有什么区别?
利用我的评论来了解问题的要点。
#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.
相关文章:
- 在将变量声明为引用时,堆在释放后使用
- 静态变量声明和定义
- 在变量声明中使用 for 循环
- 向量索引变量声明(size_t 或 std::vector<DATATYPE>::size_type)
- C++ 类型类的变量声明不命名类型?
- 将本地 OpenCV Mat 变量声明为静态以防止重新分配
- std::enable_if 更改成员 *变量* 声明/类型
- 在C++中,变量声明左侧的大括号是什么意思?
- 将变量声明为全局变量,然后声明为局部变量 -Shadowing-
- 命名空间内C++变量声明
- 将静态全局变量声明为内联有什么意义吗?
- 如何将一个变量声明为另一个变量的值
- 如何将迭代器变量声明为私有成员变量
- 没有变量声明为函数,但错误:二进制表达式的操作数无效
- 有没有人有书面证据来保证函数中参数的定义方式与普通变量声明相同?
- ClangTool 如何获取变量声明中模板参数的位置?
- 标准与显式自动推导变量声明
- C 静态变量声明怪异链接器错误
- 如何为数组成员变量声明 getter/setter
- 可视C++变量声明