Parentheses in the control expression

M

Memana

Dear Friends,
In for loop, we can define variables within the 'for' loop's
expression. Like this we can do within 'while', 'if' and 'switch'
statements, this kind of definistion is much less common than those in
'for' expressions, possibly becuase of the syntax is so constrained.

That is, there is a constraint in the syntax of the expressions of
"while", "switch" and "if" statements.

For example we cannot use parentheses as follows:
while((char c == cin.get()) != 'q')

But still I am not understanding, why parenthesis is not possible?
Does that mean that we cannot use parenthesis while defining variables
in the expressions of "while", "switch" or if" statements. ?

If any of you know, please explain...

Meman A
 
A

Alf P. Steinbach

* Memana:
Dear Friends,
In for loop, we can define variables within the 'for' loop's
expression. Like this we can do within 'while', 'if' and 'switch'
statements, this kind of definistion is much less common than those in
'for' expressions, possibly becuase of the syntax is so constrained.

That is, there is a constraint in the syntax of the expressions of
"while", "switch" and "if" statements.

For example we cannot use parentheses as follows:
while((char c == cin.get()) != 'q')

You mean,

while( (char c = cin.get()) != 'q' )

(which is still not valid due to syntax restrictions, see below.)

But still I am not understanding, why parenthesis is not possible?

The closest you can get to an answer in this group is "because!",
or more precisely, the syntax for 'condition' in the HS allows only
the two forms

expression
type-specifier-seq declarator = assignment-expression

and the "why" of such decisions belongs in [comp.std.c++], not here.

But possibly the answer you'll get is that there is no real need.

Does that mean that we cannot use parenthesis while defining variables
in the expressions of "while", "switch" or if" statements. ?

Not exactly. It means that the condition must be one of the two forms
allowed by the syntax as shown above. Mostly this also means that you
avoid errors introduced by side-effect-based code such as the above
example, which should better be coded as e.g.

assert( !cin.fail() );
for( ;; )
{
char const c = cin.get();
if( cin.fail() || c == 'q' )
{
break;
}
// Do stuff using 'c'.
}

Note that this code is not exactly equivalent to the (intuitive, if
the code were allowed) effect of your example: this code checks for
error conditions, which is always A Good Idea (TM).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top