+ 8

How to pass arrays in the functions?

Can you give me an example? Thanks

12th May 2017, 11:18 PM
Umbe
Umbe - avatar
13 Respuestas
+ 8
@aklex: Is this also true for vectors? Or just primitive types?
13th May 2017, 1:06 AM
jay
jay - avatar
+ 8
Thank you guys
13th May 2017, 8:58 AM
Umbe
Umbe - avatar
+ 7
void func(int arr[]) { } func(nameOfArray);
12th May 2017, 11:42 PM
chris
chris - avatar
+ 7
@ChrisI have heard the opposite. I believe when learning it is good practise though. Here is a thread that discusses why it is considered a bad habit: http://www.cplusplus.com/forum/unices/27805/ but at the end of the day I guess it is a personal preference.. we all have our ways Such as I prefer naming each thing I will be using like using std::cout; using std::cin; etc etc
13th May 2017, 2:39 AM
jay
jay - avatar
+ 6
@aklex: Thanks heaps!
13th May 2017, 2:31 AM
jay
jay - avatar
+ 5
whoops referenced the wrong person sorry. was meant to be @chris
13th May 2017, 2:53 AM
jay
jay - avatar
+ 3
there is no need for std:: you make your code more confusing to read just put using namespace std; on top its bad practice
13th May 2017, 2:33 AM
chris
chris - avatar
+ 1
void fff(std::array<int>& arr) { } Dont use primitive arrays, use arrays from the standard library. They are a security risk because of buffer overflows, and you also lose information about them when you pass them to functions. Even the creator of c++ himself suggests you not to use primitve arrays anymore
12th May 2017, 11:51 PM
aklex
aklex - avatar
+ 1
void func(int arr*) { } func(Array);
13th May 2017, 12:03 AM
MR Programmer
MR Programmer - avatar
+ 1
@jay, no, using vectors is fine, only primitive arrays are unsafe. You should always use std::array for static arrays and std::vector for dynamic arrays. std::map, std::pair, and all the other STL containers can be used too
13th May 2017, 2:21 AM
aklex
aklex - avatar
+ 1
@jay, yes ofc, I was referring to declaring the whole namespace globally
13th May 2017, 2:51 AM
aklex
aklex - avatar
0
@chris, actually using namespace is the bad practice. By doing that you pollute the global space with stuff that doesnt need to be there, and you also run the risk of naming conflicts. If you for example name one of your functions the same name as one from a namespace, youll have a naming conflict which will result in undefined behavior. Furthermore, it actually increases the readability. You cant tell if a function or variable is from a namespace unless you are using the scope operator like bar::foo instead of just foo.
13th May 2017, 2:38 AM
aklex
aklex - avatar