Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing typedef (fixed sized) array by value

I am having hard time understanding typedef pattern for arrays.

typedef char Char10[10];
void fun (Char10 a)  // not passing reference (interested in pass by value)
{
  if(typeid(Char10) == typeid(char*))
    throw 0;  // <--- never happens
}

int main ()
{
  char a[10];  fun(a);  // ok
  char b[11];  fun(b);  // why works ?
}

Why the different sizes of array by value are accepted by fun() ? Are char[10] and char[11] not different types ?

Edit: For those who says it decays to pointer, see my edited code. char[10] and char* doesn't seem to match.

like image 575
iammilind Avatar asked Nov 27 '22 23:11

iammilind


1 Answers

In both cases, the arrays decay to the pointer type, and your function is actually this:

void fun (char *a); 

That is why its working.

I would like to emphasize that void fun(char*) is exactly same as void fun(char[10]). The 10 doesn't make any difference at all. In fact, 10 is so unimportant and useless that you can even omit it completely as:

void fun (char a[]); //exactly same as `char*` or `char[10]`.

That means, all the following function declarations are exactly same:

void fun(char a[10]);   
void fun(char a[]);  //10 is unimportant in the above declaration
void fun(char *a);   //same as above two declarations!

Hope that clarifies your doubt.


However, if you write this:

void fun (Char10 & a) ; //note &

then, its actually this:

void fun (char (&a)[10]) ; //equivalent!

Then fun(b) wouldn't compile, as now fun will accept ONLY array of EXACTLY size 10. And the array will not decay to pointer, it will be passed by reference.

char a[10], b[11];
char *c=new char[10];
fun(a); //okay
fun(b); //error - type mismatch due to size of the array
fun(c); //error - type mismatch due to c being pointer.
like image 165
Nawaz Avatar answered Nov 29 '22 11:11

Nawaz