Re: Noob question: why the confusing syntax (data type
variable_name(value)) for initialization
On Sep 24, 1:06 am, krishna <krishna.k.0...@gmail.com> wrote:
What is the need of this syntax for initializing values, isn't
this ambiguous to function call?
History. It's generally recognized as an embarassing feature.
(I believe it has been referred to as "C++'s most embarassing
parse".)
e.g., int func_name(20); this looks like function call (of
course not totally as there is no function body), but is
declaration and initialization of an integer variable
'func_name',
You mean it looks like a function declaration, not a function
call. And it gets worse. Consider:
int f( x ) ;
Whether this declares a variable initialized with x, or a
function which takes an argument of type x, depends on whether x
is declared as a variable or a type. Or:
T1 f( T2( x ) ) ;
This is a declaration of a function, always (supposing T1 and T2
are types). Even if what you meant was to explicitly convert x
to type T2, and use it to initialize a variable of type T1.
This leads to some very strange error messages at times:
std::vector< int > v( std::istream_iterator< int >( source ),
std::istream_iterator< int >() ) ;
actually declares a function named v, which takes an
std::istream_iterator<int> as its first argument, a pointer to a
function which returns an std::istream_iterator<int> as its
second argument, and returns an std::vector<int>. Which is
perfectly legal, but when you try to use v later, as a vector,
you get some strange error messages about a function not being
legal in such and such a context.
If the language were being designed from scratch, with no
concerns of backwards compatiblity or history, I'm sure that the
declaration syntax would be significantly different. But it's
not, and wasn't. In the early days, and even now to some
extent, there is a requirement of C compatibility. And since
the declaration syntax in C is horribly broken, no matter what
C++ does with it will cause problems somewhere.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34