Multiple variable inialization

S

Swartz

Hi there.

I was wondering why the following two constructions dont work as expected:

1.) bool a, b, c, d = false;

2.) bool a, b, c, d;
a, b, c, d = false;

But the following works.
bool a, b, c, d;
a = b = c = d = false;

TIA
 
G

Gianni Mariani

Swartz said:
Hi there.

I was wondering why the following two constructions dont work as expected:

1.) bool a, b, c, d = false;

This means this :

bool a;
bool b;
bool c;
bool d = false;
2.) bool a, b, c, d;
a, b, c, d = false;

This is using the "comma" operator.

It may be re-written as;

a; b; c; d=false; // well alomost
But the following works.
bool a, b, c, d;
a = b = c = d = false;

This means :

(a=(b=(c=(d=false))));


You can do somthing like:

template < typename w_type, typename w_init_type, w_init_type w_val >
class AT_IType
{
public:

w_type m_value;

inline AT_IType()
: m_value( w_val )
{
}

inline operator w_type & ()
{
return m_value;
}

inline operator const w_type & () const
{
return m_value;
}

inline w_type & operator = ( const w_type & i_value )
{
m_value = i_value;

return m_value;
}

};

AT_IType <bool,bool,false> a, b, c, d;
 
R

Rolf Magnus

Swartz said:
Hi there.

I was wondering why the following two constructions dont work as
expected:

That depends on what you expect. They work as expected here.
 
T

tom_usenet

Hi there.

I was wondering why the following two constructions dont work as expected:

1.) bool a, b, c, d = false;

bool a = false, b = false, c = false, d = false;

You have to initialize each one separately. Often the advice in C++ is
to have only 1 variable per declaration. e.g.

bool a = false;
bool b = false;
bool c = false;
bool d = false;

is clearer.
2.) bool a, b, c, d;
a, b, c, d = false;

The comma operator is used to separate expressions and return the
right hand expression. So that is exquivalent to:
evaluate a, discard the value
evaluate b, discard the value
evaluate c, discard the value
evaluate "d = false", discard the value.
So only d is modified.

Using the comma operator in an unusual way:
a = false, b = false, c = false, d = false;
or in conventional syntax:
a = false; b = false; c = false; d = false;
But the following works.
bool a, b, c, d;
a = b = c = d = false;

It should be obvious why that works, but for the others you just have
to understand declaration syntax and the comma operator.

Tom

C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
 

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

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top