Re: declaration of a char in an if-statement fails to comile
pavel.lukin@gmail.com wrote:
the problem is briefly described in the subjec, so I'll just
give the sample code:
<code>
#include <string>
int main()
{
std::string fileName("filename.txt");
int ix = 8;
if(( char c = fileName[ix] ) == '.' )
{
c = '_';
fileName[ix] = c;
}
}
</code>
I tried to compile this with g++, MS Visual Studio Express
2005 and comeau, neither succeeded. Am I missing something
here? A clear explanation will be greatly appreciated.
I'm probably missing something, but what makes you think that
you can embed a declaration in an expression? This has never
been allowed, neither in C nor in C++. The correct way to write
this is to declare the variable before the if, e.g.:
char c = filename[ ix ] ;
if ( c == '.' ) ...
For the specific case in your example, of course, I can't
imagine using an intermediate variable. But in general, except
for the consacrated idiom involving io, it's better to avoid
side effects in conditional expressions -- they just confuse the
reader. Thus, for example, C++ allows certain, limited forms of
a declaration to be used *instead* *of* an expression when a
conditional expression is expected, but I've yet to find any use
for this feature.
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]