简体   繁体   中英

Parameters and functions in C++

Let's suppose this code:

void function(const float vect[]){

// making something with "vect" here (not modifying as it is const)

};

then in the main function:

float v[5];

function(v+2);

Is it correct to call the function like that? What exactly I'm passing to that function doing that?

The array will decay to pointer during the call

so you're basically doing this :-

+---+---+---+---+---+
|   |   |   |   |   |
+---+---+---+---+---+
 ^    ^   ^   ^   ^
 |    |   |   |   |
 v   v+1 v+2 v+3 v+4
          ^
          |
function(v+2); //In "function" v will be used from v+2, i.e. vect[0] will be v[2]

To understand this you have to understand that sometimes C++ lies.

void function(const float vect[]){ is not a function taking an array as a parameter (that's the lie). Instead it's exactly the same as if you had written this void function(const float* vect){ . Now it's easier to understand, your function takes a pointer, so when you write function(v+2); you are passing a pointer to the third element of your array, just as when you write function(v); you are passing a pointer to the first element of your array.

It's impossible to pass an array to a function in C++ (or return an array from a function), arrays are always converted into pointers in these situations.

Is it correct to call the function like that?

As long as you don't access the array out of bounds (ie you only read vect[0] , vect[1] or vect[2] ), it is.

What exactly I'm passing to that function doing that?

I don't understand this question. If you want to know what this does: the v array decays into a pointer, then the + operator performs pointer arithmetic on it, and a pointer to of the third element (ie the one at index 2) is passed to the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM