Re: declaration of a char in an if-statement fails to comile
pavel.lukin@gmail.com wrote:
Hi everyone,
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.
Yes, you're missing the simple fact that a declaration is allowed between
the 'if's parentheses, but not in an arbitrary expression. Since you've
surrounded the declaration with its own set of parentheses, the syntax
you're trying to use is not allowed. You could rewrite this as
if (char c = !(fileName[ix] - '.'))
but there is no need. Since you're not using the value of 'c' with which
it is initialised, the right way would be:
if (fileName[ix] == '.')
fileName[ix] = '_';
And you do away with 'c' altogether.
What is allowed, for example is this:
if (ifstream myfile(filename)) {
// do something with 'myfile'
}
which limits the scope of 'myfile' to that 'if' statement and its controlled
statement, and behaves similarly to
{ ifstream myfile(filenale); if (myfile) {
// do something with 'myfile'
}}
Since 'ifstream' has a conversion to 'bool' (indirectly), you could declare
and initialise it between the 'if's parentheses. You can do the same with
integral values, for example:
if (char somechar = *p++) { // means 'if somechar is not 0'
...
}
but you can't merge the declaration and actual logical expression. The
declaration has to serve as the expression. The comparison is always with
zero, not with an arbitrary value.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]