initializing static variable conditionally

May 7, 2010 at 1:48am
Hi,

I would like to know how to initialize a static variable conditionally.

if(flag == true)
{
static int jk = 4;
}
else
{
static int jk = 5;
}

int kl = jk + 34;

I would like jk to be a static variable, and initialized only once,
but conditionally. however, when I put it in an if statement, it's
scope becomes limited to the if { } region.

any ideas on how to handle this scenario?

thanks for you replies!
-sunil.
May 7, 2010 at 2:40am
why u declare jk var in if scope..u can set jk as global varible

~begin3r
May 7, 2010 at 9:35am
You can use the conditional operator:
static int jk = flag ? 4 : 5;

http://www.cplusplus.com/doc/tutorial/operators/
May 7, 2010 at 1:06pm
(However keep in mind that statics are initialized only once no matter where they are declared)
Topic archived. No new replies allowed.