c++ - When a function has a specific-size array parameter, why is it replaced with a pointer? -
given following program,
#include <iostream> using namespace std; void foo( char a[100] ) { cout << "foo() " << sizeof( ) << endl; } int main() { char bar[100] = { 0 }; cout << "main() " << sizeof( bar ) << endl; foo( bar ); return 0; }
outputs
main() 100 foo() 4
- why array passed pointer first element?
- is heritage c?
- what standard say?
- why strict type-safety of c++ dropped?
yes it's inherited c. function:
void foo ( char a[100] );
will have parameter adjusted pointer, , becomes:
void foo ( char * );
if want array type preserved, should pass in reference array:
void foo ( char (&a)[100] );
c++ '03 8.3.5/3:
...the type of function determined using following rules. type of each parameter determined own decl-specifier-seq , declarator. after determining type of each parameter, parameter of type "array of t" or "function returning t" adjusted "pointer t" or "pointer function returning t," respectively....
to explain syntax:
check "right-left" rule in google; found 1 description of here.
it applied example approximately follows:
void foo (char (&a)[100]);
start @ identifier 'a'
'a'
move right - find )
reverse direction looking (
. move left pass &
'a' reference
after &
reach opening (
reverse again , right. see [100]
'a' reference array of 100
and reverse direction again until reach char
:
'a' reference array of 100 chars
Comments
Post a Comment