Re: declaration of a char in an if-statement fails to comile
whiteflags99@hotmail.com wrote:
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.
You cannot initialize a new variable in an expression used as a
condition.
You cannot define a new variable in an expression, period.
Regardless of how the expression is used. A condition, however,
can be either an expression or a definition, although I can't
think of any reasonable use for the latter.
You must declare c as a character first, and then you can
use that construct:
std::string filename = "filename.txt";
int ix = 8;
char c;
if ( (c = filename[ix] ) == '.')
In such cases, it is preferable to initialize the variable when
it is defined, e.g.:
char c = filename[ ix ] ;
if ( c == '.' ) ...
In general, side effects in conditionals are very confusing.
There are a few consacrated idioms, such as IO, but otherwise,
side effects in conditionals should be avoided.
If the character you want to change is always in the same
place, like the period before a file extention, you might not
want to make a construct like this at all and just replace the
character outright. Valid filenames always have an extenstion
starting with a period so we can write:
filename[ filename.rfind('.') ] = '_';
If you're looking for it, it would be much better check the
results of filename.rfind first.
Of course, if the problem is one of transforming filenames, then
boost::regex has many powerful and easy to use tools to handle
this safely and elegantly.
and be perfectly fine. This line of code focuses on what we're
really doing to the string, and makes it somewhat easier to
read.
And a lot more likely to crash.
--
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! ]