Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Scope question

Status
Not open for further replies.

Valius

Programmer
Oct 20, 2000
174
US
Okay, I have a question about scope. Here is the situation:

We have the main function...let's call it Main(). Within main, I have declared a local varible...let's say char* TempVar. Now, from within Main() I call another function...Let's call it bool SubMain(). In that function I do a few things and it returns a 0. Now, I'm back in my Main() function...will TempVar have gone out of scope because I jumped to another function? Or will it still be considered in scope? I would think it would be considered in scope since I never actually totally left Main(). Here is my question from a programmers POV.

bool SubMain()
{
//Do what needs to be done
return(true);
}

void Main()
{
char *TempVar = new char[25];

strcpy(TempVar, "Testing 1 2 3");

if (!SubMain())
{
exit(0);
}
//When returning from my SubMain function, will
//TempVar still have a valid mem address or will it
//have gone out of scope?

delete TempVar;
}

I hope I have made sense. Any and all comments are very welcome so I can put this matter to rest in my mind, thanks in advance.

Niky Williams
NTS Marketing, Lead Engineer
 
Your correct, the scope of the tempVar is the brackets of Main so it still exists after the call. However, please put the line delete[] tempVar before your exit(0) line or you will have memory leaks :p

Matt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top