C++ Logo


Advanced search

C/C++ Declarations in expressions

From: J Decker <d3ck0r_at_[hidden]>
Date: Tue, 2 Feb 2021 19:41:49 -0800
I'm just going to drop this note, if anyone else is interested please pick
it up as its own thing.

Right now loop control expressions like for(), while() can
declare variables to use in the loop in the expression. But this is a
very limited functionality; I would have expected statements bound to
another statement like if, for, while, switch, etc to extend their content
to the next statement, and then in an expression allow defining variables,
which normally have a scope of just their expression.

For example a macro which might do some operation to a color might need a
temporary variable...

#define xyz(c) ( int colorTemp, colorTemp = (c & 0x00FF00 )>> 8, ... )

Yes, there are other ways to accomplish this; defining inline functions
for instance, or passing another parameter to the macro also... which
complicates refactoring from a function (which would itself be able to
define a temporary variable) to an inlined expression.

To recap a little, the proposal is basically that expressions '()' allow
variable declarations, like they already do as part of a flow control
statements, which has a scope/content that is only valid until their
associated statement or statement block ends.  Variables within an
expression would only have the scope of that expression; having no other
statements associated with it.  (ok as of C++17 if() statements have the
same funcionality as other flow control statements; I guess the scope would
also include the else clause?  And then all other nested if-else
expressions also have the variable defined?)

Received on 2021-02-02 21:42:02