I commonly have code where I want to detect some condition, and if it exists, then process that condition.
The test for the condition extracts certain information that is important to the processing half of the problem.
However, if/else constructs fail to allow one to declare local-to-the-if variables in the if construct itself(1). Hence, I have to put variable declarations before the beginning of the entire if/else chain for all of the various conditions for which information may be extracted.
For example:
else if ((EndsWithToken("d") || EndsWithToken("dsh")) &&
(p1 = find(m_input_line, '[')) &&
(p2 = find(m_input_line, ']')) &&
p2 > p1)
{
// process what we found inside of the [ ] brackets using p1 and p2...
}
This snippet is part of a long chain of if/else’s, and the others don’t need p1 and p2 – but they might need an integer value that was extracted from the input stream, or a double, or two points, or whatever….
The point is, there is no way that I know of introduce const TCHAR * p1 and p2 locally to the above scope, the only place it is used, that still allows for the overall structure to remain the same.
Is there some C++ language feature or a pattern that might allow for this?
(1) As some have pointed out, it is possible to declare a single variable of fundamental type, if it is the fist thing, and to test it against non-zero only. This is far too limited to be of much use as a general solution to this issue (though the occasional moment could come up where it is useful – but truly rare).
One solution would be to make each case a distinct function, that returns whether or not it succeeded.
This gives you a natural well-localized scope for the variables, and hopefully (assuming) a reasonable compiler can inline them.