Thursday, January 08, 2015

Passing an array by reference

I am blessed to have colleagues to debate with, interesting ones. Today's was about passing an array as a reference. Usually one ends-up passing the array as pointer and the size in the second parameter.

Given below is the code where one is able to pass to a function an entire array of fixed size:


#include <iostream>

int func10(int (&tenIntArray)[10])
{
for (int i = 0; i < 10; i++)
{
if (i == 0) continue;
tenIntArray[i] = tenIntArray[i - 1] + 1;
}
return 0;
}

// Only to show how it is typedef'd
typedef int FiveIntArray[5];

int func05(FiveIntArray &fiveIntArray)
{
return 0;
}

int main(int argc, char* argv[])
{
int tenIntArr[10] = { 1 };
FiveIntArray fiveIntArr = { 1 };

func10(tenIntArr); // we can't pass fiveIntArr here

for (int i = 0; i < 10; i++)
{
std::cout << tenIntArr[i] << std::endl;
}

func05(fiveIntArr); // a tenIntArr is not acceptable here

return 0;
}


It is easier to understand if one has typedef it.

The general rule with the use of typedef is to write out a declaration as if you were declaring a variable of the type you want. Where the declaration would have given a variable name of the particular type, prefixing the whole thing with typedef gives a new type-name instead. The new type-name can then be used to declare new variables.

No comments: