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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With