Noob question about scope.

The Partridge Family were neither partridges nor a family. Discuss.
Numbtea
Posts: 4
Joined: October 28th, 2017, 10:27 am

Noob question about scope.

Post by Numbtea » October 28th, 2017, 10:49 am

Hi all,

I'm just about to start tutorial 5 right now so still new to this, one things confusing me though.

The concept of 'scope' makes sense to me but it appears to have some exceptions. See here. (Shortened version for ease of viewing).

Code: Select all

void Game::UpdateModel()
{
if (wnd.kbd.KeyIsPressed(VK_UP))
	{
		if (InhibitUp)
		{
		}
		else
		{
			VY = VY - 1;
			InhibitUp = true;
		}
	}
        ShapeIsChanged = wnd.kbd.KeyIsPressed(VK_SHIFT);
	ColorIsChanged = wnd.kbd.KeyIsPressed(VK_CONTROL);
	x = x + VX;
	y = y + VY;
}
void Game::ComposeFrame()
{

	if (ColorIsChanged) <-- *How does this know to execute the putpixel in ComposeFrame() if color/shape is changed - as the key to change to bool is in the previous 'scope section/curly brackets'... 
Hold on a sec... Is this because the bool is in game.h which makes the boolean value persistent? Is this correct?

User avatar
Yumtard
Posts: 575
Joined: January 19th, 2017, 10:28 pm
Location: Idiot from northern Europe

Re: Noob question about scope.

Post by Yumtard » October 28th, 2017, 11:31 am

These are member variables. They're declared in the h file meaning the whole class will have access to them.
In update you're just modifying their values, not declaring them.

it would be a different story if you tried to do this in update:

bool ShapeIsChanged = wnd.kbd.KeyIsPressed(VK_SHIFT);
bool ColorIsChanged = wnd.kbd.KeyIsPressed(VK_CONTROL);

Numbtea
Posts: 4
Joined: October 28th, 2017, 10:27 am

Re: Noob question about scope.

Post by Numbtea » October 28th, 2017, 12:01 pm

Thanks for your response, I understood the first part more than the second.

Are you saying that if you took the values out of the h file and placed them within the separate functions they wouldn't work?

User avatar
Yumtard
Posts: 575
Joined: January 19th, 2017, 10:28 pm
Location: Idiot from northern Europe

Re: Noob question about scope.

Post by Yumtard » October 28th, 2017, 12:31 pm

int myVariable;

^ this declares a variable called myVariable

myVariable = 20;

^ this assigns a value to that variable

int myVariable = 20;

^ this both declares and assigns a value.


bool ShapeIsChanged and bool ColorIsChanged are both declared in the h file. This means that all the functions in the class will have access to them, you can write
ShapeIsChanged = true; in the updatefunction and then use the variable in the ComposeFrame function.

however if instead, you wrote this in update

bool ShapeIsChanged = true;

^ now you just declared a new variable with the same name which will only exist inside of the update function.

After this, whenver you try to use or modify the value of ShapeIsChanged it will use the new local variable you created in update.
then when you get to composeFrame that new variable is out of scope and no longer exists, so it would be using the member variable.

albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Re: Noob question about scope.

Post by albinopapa » October 28th, 2017, 6:40 pm

Might be worth it to note that it's not just because you have declared the two bools in question in the .h file, but declared them in the Game class which is what makes them members of Game. You could have just as easily made a class in the .cpp file and put the vars in there. This still makes them members of that class and that class's functions would have access to them, just like Game::UpdateModel() and Game::ComposeFrame() have access to Game::ShapeIsChanged and Game::ColorIsChanged.

There is global scope where you would declare a variable in the .h file outside of any class/union/struct or even namespace. This would allow any header or source file to be able to access that variable when that header file is #included. You have to be careful though about doing this. Global variables are usually a bad idea and the compiler will complain unless you decorate them correctly, look up static or extern for further information.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com

Numbtea
Posts: 4
Joined: October 28th, 2017, 10:27 am

Re: Noob question about scope.

Post by Numbtea » October 30th, 2017, 6:06 pm

Ooh okay, I can see what your saying now.
As for the structure of the framework I'm still a bit unsure of what certain pages do/are there for but I'm sure as I go through the tuts some more things should piece together.
Also - what your saying albinopapa is that there's a level above the h file that everything can access,but its risky business?

albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Re: Noob question about scope.

Post by albinopapa » October 30th, 2017, 11:33 pm

There is global scope which means it's in a header, but outside of any namespace or class.
There is file scope, which you can put a variable in a CPP file outside of any namespace, class or function and only that file can interact with it.
There is member scope ( don't know if that is what it's real name is ) where you have a variable in a class, struct or union ( all considered class types ).
Then there is local scope. This can be anything between { and } inside a function.

Code: Select all

void Foo()
{ // begin scope A
// This is one scope
     { // begin scope B
          // This would be limiting the scope even further inside the same function
          //
     }// End scope B
} // End scope A
You'll often see chili use this scoping inside functions to be able to reuse variable names within the same function

Code: Select all

void Foo()
{
     const int a = 42;
     const int b = 27;
     const int c = 118;
     {
          const int result = a + b;
          // Do something with result
     }
     {
          const int result = a + c;
          // Do something else with result;
     }
}
One reason for doing this is so you can make the result const, which helps optimize your code during compilation. Without it, you'd have two options, have each result be a different name in order to keep them const, or lose the const and rewrite the second result to the result variable.

Another reason might be for multi-threading where you need to lock other threads while the current thread is working on shared data. You don't want to lock for longer then needed, so you might use a scoped guard that when the scope ends, the other threads are allowed to continue their work. Without mechanism, you'd be responsible for locking and unlocking manually, or have to wait for the end of the function which is a waste of time.

There is also something called static scope. One case is if you define a static variable inside a function, it is put in the same place as global memory, but can only be interacted with during that function call.

Code: Select all

void Foo()
{
     static int s_val = 42;     
}
You can change the value, it is remembered between calls and it doesn't get reinitialized back to 42 each time. It never dies until you end your program.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com

albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Re: Noob question about scope.

Post by albinopapa » October 30th, 2017, 11:47 pm

Global variables are often frowned upon unless they are constant values. One good use for a global variable would be the value for PI. It never changes and you wouldn't want to have to write out 3.1415926f every time you needed to do something with PI.

There are reasons for not using global variables, however I don't have any off the top of my head. I think it's just better to keep variables with the objects you are going to use them with. If you have a class that has data that doesn't change between instances ( all the same width and height ), then put width and height in the class, but make them static. This means the width and height are a part of the object, but not a part of the object's memory.

Code: Select all

class Unit
{
public:

private:
     static float width, height;
};

Unit.cpp
// Static non-const members have to be defined separately in the cpp file.
float Unit::width = 32.f;
float Unit::height = 32.f;

Unit::Unit( float W, float H )
{
     // Can be changed in the constructor body
     width = W;
     height = H;
}
Since they are a part of the Unit class and is set to private, they cannot be changed directly outside of the Unit class. This might be one reason globals are considered bad. They can be changed to mean different things, so if their context changes somewhere down the line, you've introduced a bug that might be a bitch to find. To elaborate, if you have a global variable that might store nUnits ( number of enemy units to spawn ) and someone else or you forget that's what it was for and change the meaning to number of bullets to spawn, now either the number of enemies spawning will not be what you want or the number of bullets spawning will not be what you want.

It's a poor example, but the best I have and could happen when you start getting tired and your code is getting large and out of hand.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com

Numbtea
Posts: 4
Joined: October 28th, 2017, 10:27 am

Re: Noob question about scope.

Post by Numbtea » November 1st, 2017, 7:27 pm

Wow, thanks so much for the response, you really went in depth! This has cleared up the questions i had, and introduced me to a few new things that I'm sure to encounter soon.

I'll keep chopping away at the tutorials and hopefully progress will be made... great to see the help is available though for when myself and others get a bit confused :) Really appreciate it, thanks!

User avatar
LuisR14
Posts: 1248
Joined: May 23rd, 2013, 3:52 pm
Location: USA
Contact:

Re: Noob question about scope.

Post by LuisR14 » November 1st, 2017, 8:15 pm

the different, available scopes I consider are static, global, file, namespace, class, function, and block.
global and file are basically the same (and is equal to the global namespace)
always available, always on, about ~10 years c/c++, java[script], win32/directx api, [x]html/css/php/some asp/sql experience. (all self taught)
Knows English, Spanish and Japanese.
[url=irc://irc.freenode.net/#pchili]irc://irc.freenode.net/#pchili[/url] [url=irc://luisr14.no-ip.org/#pchili]alt[/url] -- join up if ever want real-time help or to just chat :mrgreen: --

Post Reply