将数组传递给函数和在main中声明数组有什么区别?
What is the difference between passing arrays to function and declaring array inside main?
将数组传递给function和在main中声明数组有什么区别?每个结构的优点是什么?例如,在第一个代码示例中,我将数组传递给一个函数,在第二个代码示例中,我在main中声明它。有什么区别?
版本1:#include <iostream>
using namespace std;
void printArray(int theArray[], int sizeofArray);
//passive arrays to function..
int main() {
int arr[3] = {44,23,22};
int arry[5] = {56,23,11,23,55};
printArray(arr, 3);
}
void printArray(int theArray[], int sizeofArray){
for(int x =0;x<sizeofArray; x++){
cout << theArray[x] << endl;
}
}
版本2:#include <iostream>
#include <string.h>
using namespace std;
int main() {
int arr[3] = {44,23,22};
int arry[5] = {56,23,11,23,55};
for(int x=0;x<3;x++){
cout << arr[x] << endl;
}
}
正如Juanchopanza所指出的,在这两种情况下,您的数组都是在main
函数中声明的。
主要区别在于代码组织。函数的目的是允许您对不同的参数执行任务。在第二个示例中,您仍然可以执行printArray(arry, 5)
来打印第二个数组的内容,如下所示:
#include <iostream>
using namespace std;
void printArray(int theArray[], int sizeofArray);
//passive arrays to function..
int main() {
int arr[3] = {44,23,22};
int arry[5] = {56,23,11,23,55};
printArray(arr, 3);
printArray(arry, 5); // Let's see what's inside arry too !
}
void printArray(int theArray[], int sizeofArray){
for(int x =0;x<sizeofArray; x++){
cout << theArray[x] << endl;
}
}
如果你想在第一个例子中做到这一点,你必须复制/粘贴循环,这将导致代码可读性降低,看看它有多难看:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
int arr[3] = {44,23,22};
int arry[5] = {56,23,11,23,55};
for(int x=0;x<3;x++){
cout << arr[x] << endl;
}
for(int x=0;x<5;x++) { // Here
cout << arry[x] << endl;
}
}
如果你必须打印十个不同的数组会发生什么?你是喜欢用不同的参数调用函数printArray
十次还是你会复制/粘贴你的循环十次?
相关文章:
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 为什么从函数返回数组时需要将数组声明为静态数组.(C++)
- 在 c++ 中直接访问的内联数组声明
- 由于 2D 数组声明,C++ 14 中的运行时错误
- 如何将char数组声明为函数参数?或告诉我此代码中还有其他问题?
- 来自函数参数的 C++ 静态数组声明
- C++ 中的动态数组声明
- C++数组声明
- 数组声明中的错误:表达式必须具有常量值
- 程序随数组声明崩溃
- 运行时和编译时的数组声明
- C++数组声明和初始化
- 带有常量表达式的数组声明
- C ,数组声明,模板,链接器错误
- 如何用'n'维数组声明 std::vector?
- 数组声明上的编译器错误
- 这是什么数组声明
- 头文件类中的数组声明
- 节点数组声明
- 在静态数组声明中使用了两次C++常量