局部变量和全局变量
Python程序
def f():
print(a)
if __name__ == "__main__":
a = 1
f()
和
def f():
print(a)
a = 1
if __name__ == "__main__":
f()
输出结果都是1。
C++程序
#include <iostream>
int a = 1;
void f()
{
std::cout << a << std::endl;
}
int main()
{
f();
return 0;
}
输出结果1,而程序
#include <iostream>
void f()
{
std::cout << a << std::endl;
}
int main()
{
int a = 1;
f();
return 0;
}
报错:“a”: 未声明的标识符。
形参和实参
Python程序
def f(a, b):
a[0] += 1
b += 1
print("f:", a, b)
if __name__ == "__main__":
a = [1, 2]
b = 1
f(a, b)
print("main:", a, b)
和
import numpy as np
def f(a, b):
a[0] += 1
b += 1
print("f:", a, b)
if __name__ == "__main__":
a = np.array([1, 2])
b = 1
f(a, b)
print("main:", a, b)
的输出都是:
f: [2, 2] 2
main: [2, 2] 1
说明在函数中修改list或者array的值会影响函数外原list或者原array的值,而修改int的值不会影响函数外原int的值。若把 a = [1, 2]换成a = (1, 2)则报错:‘tuple’ object does not support item assignment;换成a = {1, 2}则报错:‘set’ object is not subscriptable。
C++程序
#include <iostream>
void f(int* a, int b)
{
a[0] += 1;
b += 1;
std::cout << "f:{" << a[0] << ", " << a[1] << "} " << b << std::endl;
}
int main()
{
int a[] = { 1, 2 };
int b = 1;
f(a, b);
std::cout << "main:{" << a[0] << ", " << a[1] << "} " << b << std::endl;
return 0;
}
的输出结果
f:{2, 2} 2
main:{2, 2} 1
和Python的类似。而C++程序
#include <iostream>
#include <vector>
void f(std::vector<int> a, int b)
{
a[0] += 1;
b += 1;
std::cout << "f:{" << a[0] << ", " << a[1] << "} " << b << std::endl;
}
int main()
{
std::vector<int> a = { 1, 2 };
int b = 1;
f(a, b);
std::cout << "main:{" << a[0] << ", " << a[1] << "} " << b << std::endl;
return 0;
}
输出结果
f:{2, 2} 2
main:{1, 2} 1
说明在函数中修改vector的值不会影响函数外原vector的值。