Re: if(T p = a()) + else = Bah!
On 17 Nov., 14:49, "Martin B." <0xCDCDC...@gmx.at> wrote:
Sometimes the C++ syntax really leaves me baffled:
/////////////////////////
typedef int T;
T a() {
return 0;
}
int main()
{
if(T p = a()) {
p; // in scope, not null - compiles OK
}
else {
p; // in scope - compiles OK
}
p; // out of scope - error: undeclared identifier
// Note that an inverse condition, where p would
// have an actually useful value inside
// the else block won't compile:
if(!(T p = a())) { // syntax error
p;
}
I don't see the convincing advantage over
if (T p = !a()) {
!p;
}
return 0;}
//////////////////////////
Now, what kind of sense does it make that p is still in scope in the
else block? It's always false/0/NULL there anyway! *shakeshead*
There are several reasons for this:
1) It ensures a consistency between if and else, because both
have the same scoping level and are based one the same "root"
element - the /condition/ of the selection-statement.
2) Your argument that inside the else clause the value of p is
always false/0/NULL is misleading for two reasons:
a) With the same argument one could point out that inside
the if-statement p is always true/!0/!NULL, so this is no
convincing argument at all.
b) If p is not a scalar, but a user-defined class-type, it may
have completely different state values within the if- and
the else-statement, e.g.:
class State {
std::vector<WhatEver> data;
Something other;
public:
...
operator bool() const {
return /.../; // Compute result from internal state
}
};
State a();
void test() {
if (const State& s = a()) {
// use s here
} else {
// use s here
}
}
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]