Advertisement

How can i set local variable to global variable in C++ ?

Started by July 30, 2017 10:38 AM
22 comments, last by MarcusAseth 7 years, 4 months ago

@Asokanta If you go back and read my third reply, probably now you would see that is the same solution you are using, so I hope you'll see that the -1 was uncalled for, and if you simply asked for an example, I would have provided that as well.

 

@Scouting Ninja Correct me if I'm wrong, but is your method keeping the variable around becuase needed by the function you declare after?

If so, why not using the static keyword instead on the variable declaration and omit writing that function? There is any advantadge in doing it the way you suggested?

2 hours ago, MarcusAseth said:

@Scouting Ninja Correct me if I'm wrong, but is your method keeping the variable around becuase needed by the function you declare after?

The reason for doing what I did is because you want a local value yet not the variable.

For example:


//Sorry my C++ is rusty so this is more like C#, the idea is the same.

void MultiplyByTen(int NumberToMultiply){
 int TheTen = 10; //A local variable when the function is done this will be marked for trash collection
 return TheTen * NumberToMultiply;
}

int TheAnswer = MultiplyByTen(5); // TheAnswer now equals 50;
TheAnswer = MultiplyByTen(8); // TheAnswer now equals 80;
//So you can see this is a small program, I can use it as I want.

//Mostly it's used for instancing so that each instance has it's own local var.
class AEnemy(){
int Health = 100;
int Mana   = 100;
  
  void DamageEnemy(int InDamage){
    Health -= InDamage;
  }
  
  int GetHealth(){
    return Health;
  }
}

//Now We make more than one enemy
EnemyA = new AEnemy();
EnemyB = new AEnemy();

//Do damage to one
EnemyA.DamageEnemy( 20);
//Get the health of both
EnemyA.GetHealth(); //Will return 80
EnemyB.GetHealth(); //Will return 100

Return is a way to retrieve a local variable. It was not the best way to solve the above post, it's just one more way to do it.

Returning is also used a lot when dealing with arrays and lists.

2 hours ago, MarcusAseth said:

There is any advantadge in doing it the way you suggested?

No your way was the best for the code related to the post, the way you explained by placing the variable as a global is known as batching. It allows the reuse of the variable if one or more program needed it.

Your way is better because it's cleaner and easy to use.

Instancing works best with many objects of the some type, batching works best for many different programs using the same kind of variable.


//Batch example

int BatchCounter; //Global variable for use by all

void PrintTenNumbers(){
 BatchCounter = 0; //Here we reset the batch for use
 while (BatchCounter =< 10){
       BatchCounter +=1;
       print( BatchCounter);               
     }
}

void PrintBobTenTimes(){
  BatchCounter =0; //Reset again for use by the new function
   while (BatchCounter =< 10){
       BatchCounter +=1;
       print("Bob");    
     }
}

PrintTenNumbers(); // Prints 1 2 3 4 5 6 7 8 9 10
PrintBobTenTimes(); // Prints Bob Bob Bob Bob Bob Bob Bob Bob Bob 

//By using one int variable, instead of two, we saved a small amount of memory (1byte) not much

So saving one byte isn't much. Yet consider the AEnemy class, with Health and Mana it's a +/- 2byte class.

So if we had a lot of programs that needed AEnemy class, we could use a batch to hold one.

2bytes isn't much, yet games often have much more complex classes, with visual elements, they can range around 100MB-1GB. Suddenly batching becomes very important.

Advertisement

I was curious about this because it remembered me the way you get a persistent variable in Lua, and I never saw it done in C++, so now I'm testing it with your code:


#include <iostream>
using namespace std;

void GetSetting()
{
	//Declare the aviable above
	double Z2;
	//Make a get function here:
	double GetTheVariable() {
		return Z2;
	}

}

int main()
{


	return 0;
}

And it won't compile :/

I google a bit, and it seems in C++ you cannot declare a function into a function, anyone please correct me if I got this wrong, because this is getting me confused quite a bit :D

1 hour ago, MarcusAseth said:

I google a bit, and it seems in C++ you cannot declare a function into a function, anyone please correct me if I got this wrong, because this is getting me confused quite a bit :D

My mistake I have been using python for way to long now.

You are right C++ does not support nested functions. So it needs to be inside a class or struct.

It does support nested classes.




#include <iostream>

int staticScopedToFunction() {
	static int x = 0;		//persists entire program
	return ++x;				
}

int moduleScoped = 10;	//persists entire program

int main() {


	int localScoped1 = 4; //persists with main

	//this is called a lambda fuction, google is wise in its ways
	auto localFunc = [&](int a) -> int {
		int b = 2;		//created at function call, persists for duration of function, along with a

		return a + moduleScoped + b
			+ localScoped1; //& lets us see localScoped1;
	};

	int localScoped2 = 5; //persists for the duration of the function or epoch it's in, 
						  //in this case, main - the remainder of the program
	int r = localFunc(localScoped2) + staticScopedToFunction();

	std::cout << r 
		<< " press enter key when done";

	std::cin.get();
}

 

On 7/30/2017 at 2:08 PM, Scouting Ninja said:

My mistake I have been using python for way to long now.

You are right C++ does not support nested functions. So it needs to be inside a class or struct.

It does support nested classes.

You can sort of get there using lambdas...


int f()
{
  auto g = []() -> void
  {
    printf("In g\n");
  };
  
  printf("In f\n");
  g();
}

 

Advertisement

Well, since we are writing weird stuff, let me joing the party with 


#include <iostream>
using namespace std;

auto myFunction()
{
	int(*f)() = []() { int myVariable = 0; return ++myVariable; };
	return f;
}

int main()
{
	while (true){
		cout << myFunction()();
	}
}

:D

That's right, this way one can put a function into a function, though the original point was to have the variable persist so the static keyword is kind of unavoidable it seems, either that or the global.

And if the static keyword is used inside the function (which in the OP example wasn't main), then there is really no point in wrapping it in another function I think 

By the way, in the code above, why does 


auto myFunction()
{
	int(*f)() = []() { int myVariable = 0; return ++myVariable; };
	return f;
}

compile while the code below doesn't?


int(*)() myFunction()
{
	int(*f)() = []() { int myVariable = 0; return ++myVariable; };
	return f;
}

How would you write the second snippet function return type in a valid way, without using auto or trailing return or typedefs or using keyword?

EDIT: ok, found :D


int(*myFunction())()
{
	int(*f)() = []() { int myVariable = 0; return ++myVariable; };
	return f;
}

 kind of off topic, I apologize :D

This topic is closed to new replies.

Advertisement