User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the C++ section within the Software Development category of DaniWeb, a massive community of 423,615 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,242 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our C++ advertiser: Programming Forums

Variable scope problem

Join Date: Sep 2004
Posts: 6,306
Reputation: Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of Narue has much to be proud of 
Rep Power: 28
Solved Threads: 456
Super Moderator
Narue's Avatar
Narue Narue is online now Online
Expert Meanie

Re: Variable scope problem

  #4  
Sep 11th, 2007
>Provided I cannot make define the object globally or at the start of main().
You have to define a variable before it's used, and you have to define a variable within a visible scope. What you're doing is illegal because g1 is defined in a nested scope but used beyond that scope. It has to be like this:
int main()
{
  // ...
  Graph g1;

  if ( var )
    g1 = CreateGraph<Graph> ( vertex, edge );
  else
    g1 = CreateGraph<Graph1> ( vertex, edge );

  numvertex ( g1 );
}
>Provided I cannot make define the object globally or at the start of main().
If the unnamed block trick doesn't count, you're SOL:
int main()
{
  // ...

  {
    Graph g1;

    if ( var )
      g1 = CreateGraph<Graph> ( vertex, edge );
    else
      g1 = CreateGraph<Graph1> ( vertex, edge );

    numvertex ( g1 );
  }
}
However, I fail to understand why you have this restriction. Perhaps you can enlighten us as to what program requirements are stopping you from defining a variable in the correct scope?
I'm a programmer. My attitude starts with arrogance, holds steady at condescension, and ends with hostility. Get used to it.
Reply With Quote  
All times are GMT -4. The time now is 9:02 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC