dq 喜欢用这个表达. 专门查一下, 备忘.
实参对应 argument, 是函数调用的时候真正扔进去的参数.
形参对应 parameter, 是函数定义的时候对将要被扔进去的东西的指代.
有时候大家会混着说.
"We will generally use parameter for a variable named in the parenthesized list in a function definition, and argument for the value used in a call of the function. The terms formal argument and actual argument are sometimes used for the same distinction."——《The C Programming Language》Section 1.7 K&R
可以看到实参和形参这两个说法其实来自 actual argument 和 formal argument.
区分形参和实参, 主要是因为
- 虽然它们看上去是一个东西, 从不同 scope 有不同的叫法;
- 但实际上, 他们不是同一个变量
比如
void swap(int a, int b) {
int tmp = a;
a = b;
b = tmp;
}
int A = 1111;
int B = 2222;
swap(A, B);
A 和 B 是实参, 但进入函数后那个 a 和 b, 虽然可以指的同一个东西, 但对变量 a, b 的操作, 不会影响到 A 和 B.
这似乎和值语义的概念有关. 值对象到了函数里面, 对它的操作不再反映回外部 (除非你 return).
对象语义的话, 不太一样. 因为对象可以保存状态, 它对它 refer 的东西修改, 可以反映到外面.
当然, 对象当变量看, 可以保存的两个层面的状态, 一个是对象的状态, 一个是... 更宏观的对象的状态. 对应下面两种情况的代码:
// 改变对象的状态 (p1 和 p2 都改变了, 且可以反映到外部)
void swapAge(Person p1, Person p2) {
int tmp = p1.getAge();
p1.setAge(p2.getAge());
p2.setAge(tmp);
}
// 改变对象的状态 (改变了形参 p1, 虽然并没有什么卵用, 但在函数内, 状态确实发生了迁移)
void swapPerson(Person p1, Person P2) {
p1 = p2;
}
reference