Skip to main content
GameDev.net gamedev.net
🔒 Locked

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

Started by Asokanta Jul 30, 2017 at 10:38 AM 22 replies 5.4k views
Original Post
Asokanta
Asokanta

Hello guys,i created a config file and got line by line then parsed to variables.How can i set local (function) variable to global variable ? sorry for bad english.

Current code:



void GetSettings()
{
	ifstream nameFileout;
	nameFileout.open("Settings.conf");
	string line;
	if (!nameFileout.is_open())
	{
	
		exit(0);
	}
	while (std::getline(nameFileout, line))
	{

		string parse = "[Zoom]-10";
		stringstream ss(parse);
		string temp = "[Zoom]";

		getline(ss, temp, ']');
		getline(ss, temp, '[');

	double Result;
	stringstream convert(temp);
	double Z2 = atof(temp.c_str());

		AllocConsole();
		freopen("CONOUT$", "w", stdout);
		std::cout << line << std::endl;
	}
	nameFileout.close();

}

Output :


Z2 = -10
Asokanta™ Working for freelance own project.If you want help or get information just send private message. ______________________________________________________________________________ All the links of Asokanta™ nick-name.ru/nickname/Asokanta/
MarcusAseth
MarcusAseth

You need to put the variable on top of the function, outside of it.

If you place it inside the function then the scope of that variable is the function block and goes out of scope at the end of it, therefore is not global.

Asokanta
Asokanta

I know i need put out of function and top of the code but i don't know how.

Asokanta™ Working for freelance own project.If you want help or get information just send private message. ______________________________________________________________________________ All the links of Asokanta™ nick-name.ru/nickname/Asokanta/
MarcusAseth
MarcusAseth
5 hours ago, Asokanta said:

I know i need put out of function and top of the code but i don't know how.

Lol. (the complexity of your qurstion is below the complexity of the code you're dealing with)

Just copy the line where you declare that variable and paste it right before the function (on top of it), and delete the one inside of it

Asokanta
Asokanta

code in the function.If i remove the function and just write double Z2 = -10 it won't getsettings from config file...

Asokanta™ Working for freelance own project.If you want help or get information just send private message. ______________________________________________________________________________ All the links of Asokanta™ nick-name.ru/nickname/Asokanta/
MarcusAseth
MarcusAseth

You declare the variable outside the function, and then you use it inside by using the variable name, without declaring the type again (so if is a string, you won't write "string parse = ..." inside the function but you directly use "parse = ...").

Asokanta
Asokanta
Just now, MarcusAseth said:

You declare it the variable outside the function, and then you use it inside by using the variable name, without declaring the type again (so if is a string, you won't write "string parse" inside the function but you directly use "parse = ...").

Also if is you who gave me -1 on the previous reply, please remove it since it answers what you asked on the first post, so is not my fault if you didn't get it :/


17 minutes ago, Asokanta said:

Hello guys,i created a config file and got line by line then parsed to variables.How can i set local (function) variable to global variable ? sorry for bad english.

Current code:




void GetSettings()
{
	ifstream nameFileout;
	nameFileout.open("Settings.conf");
	string line;
	if (!nameFileout.is_open())
	{
	
		exit(0);
	}
	while (std::getline(nameFileout, line))
	{

		string parse = "[Zoom]-10";
		stringstream ss(parse);
		string temp = "[Zoom]";

		getline(ss, temp, ']');
		getline(ss, temp, '[');

	double Result;
	stringstream convert(temp);
	double Z2 = atof(temp.c_str());

		AllocConsole();
		freopen("CONOUT$", "w", stdout);
		std::cout << line << std::endl;
	}
	nameFileout.close();

}

Output :



Z2 = -10

//global variables
double X2 = 0.0f;
double Y2 = 0.0f;
// double Z2 need to be here.

i'm trying to make this but i can't remove the function and don't know how to declare without this function can u be more specify like write code ?

Asokanta™ Working for freelance own project.If you want help or get information just send private message. ______________________________________________________________________________ All the links of Asokanta™ nick-name.ru/nickname/Asokanta/
rip-off
rip-off

Can you show us your current code, after you tried making the variable global?

Asokanta
Asokanta
Just now, rip-off said:

Can you show us your current code, after you tried making the variable global?

I'm getting settings(variables) from this code :


void GetSettings()
{
	ifstream nameFileout;
	nameFileout.open("Settings.conf");
	string line;
	if (!nameFileout.is_open())
	{
	
		exit(0);
	}
	while (std::getline(nameFileout, line))
	{

		string parse = "[Zoom]-10";
		stringstream ss(parse);
		string temp = "[Zoom]";

		getline(ss, temp, ']');
		getline(ss, temp, '[');

	double Result;
	stringstream convert(temp);
	double Z2 = atof(temp.c_str());

		AllocConsole();
		freopen("CONOUT$", "w", stdout);
		std::cout << line << std::endl;
	}
	nameFileout.close();

}

This function's output is here :


double Z2 = -10;


But i wan't use this Z2 like this global variables :


//Global Variables
double rotated_y = 0.0;
double rotated_x = 0.0;
double rotate_y = 0.0;
double rotate_x = -65.0;
double zoom = 90.0;
//String Variables
string Var1 = "[Zoom]";
string null = "\0";
//Camera Variables
double X2 = 0.0f;
double Y2 = 0.0f;
// double Z2 need to be here.
//Movement Variables
double X1 = 0.0f; // ←→
double Y1 = 0.0f; //  ↕
double Z1 = 0.0f; // 
double speed = 1.0f;
//Colission Variables
bool CanMoveToLeft = true;
bool CanMoveToRight = true;
bool CanMoveToUp = true;
bool CanMoveToDown = true;


Asokanta™ Working for freelance own project.If you want help or get information just send private message. ______________________________________________________________________________ All the links of Asokanta™ nick-name.ru/nickname/Asokanta/
rip-off
rip-off

I've hidden some negative comments that weren't helping. Please, be respectful and understanding of one another.

Scouting Ninja
Scouting Ninja
46 minutes ago, Asokanta said:

How can i set local (function) variable to global variable ?

You cant set a local to global it needs to be returned

So:


void GetSettings()
{
	ifstream nameFileout;
	nameFileout.open("Settings.conf");
	string line;
    //Declare the aviable above
    double Z2;
    //Make a get function here:
    double GetTheVariable(){
      return Z2;
    }
  
	if (!nameFileout.is_open())
	{
	
		exit(0);
	}
	while (std::getline(nameFileout, line))
	{

		string parse = "[Zoom]-10";
		stringstream ss(parse);
		string temp = "[Zoom]";

		getline(ss, temp, ']');
		getline(ss, temp, '[');

	double Result;
	stringstream convert(temp);
    //Use the variable here as a pointer
	Z2 = atof(temp.c_str());

		AllocConsole();
		freopen("CONOUT$", "w", stdout);
		std::cout << line << std::endl;
	}
	nameFileout.close();
  
//Use something like this where you need it
  double A2 = GetSettings.GetTheVariable(); //Should return: atof(temp.c_str())

You could have found this by searching the net for 10 seconds.

http://www.cplusplus.com/forum/beginner/2097/

rip-off
rip-off

In your updated code, you have not declared a global variable "Z2". It is not clear to me whether you really want to introduce a new global variable, or whether you want to update one of your existing variables from the configuration settings.

In general, setting a global variable is done like so:


#include <iostream>

int global = 13;

void changeValue()
{
    global = 42;
    std::cout << "Changed value: " << global << std::endl;
}

int main()
{
    std::cout << "Starting value: " << global << std::endl;
    changeValue();
    std::cout << "Updated value: " << global << std::endl;
}

If you want to declare a new variable, then you need to add it to those globals like you have done for the others. The other thing to be careful of is to not declare a local variable with the same name:


#include <iostream>

int confusing = 13;

void changeValue()
{
    int confusing = 42;
    std::cout << "Changed value: " << confusing << std::endl;
}

int main()
{
    std::cout << "Starting value: " << confusing << std::endl;
    changeValue();
    std::cout << "Updated value: " << confusing << std::endl;
}

If you run this, you'll notice that the global has not been updated. This is because a new variable with the same name was introduced in "changeValue".

rip-off
rip-off

I've hidden some more unhelpful replies.

To Asokanta, this is not a real time chat. Please have patience and wait for a reply. Also understand that we're not here to write your code for you, but to help you learn how to write your own code.

To others, please bear in mind that Asokanta is relatively new to this and what might seem like a straightforward suggestion could be confusing or not very obvious.

All future replies should be respectful and on topic. Failure to follow these instructions will result in moderation action being taken.

Asokanta
Asokanta

There is no member write code for me i just wan't be more specify like example code :D and i will try this codes

1 hour ago, Scouting Ninja said:

You could have found this by searching the net for 10 seconds.

http://www.cplusplus.com/forum/beginner/2097/

i tried google and i just found other private forums but i didin't understood and i created a topic from here.

Thank you guys helping me anyway :D.

Asokanta™ Working for freelance own project.If you want help or get information just send private message. ______________________________________________________________________________ All the links of Asokanta™ nick-name.ru/nickname/Asokanta/
Asokanta
Asokanta

Thank you guys it's working now.Topic can be locked.

The last code is here :


void GetSettings()
{
	ifstream nameFileout;
	nameFileout.open("Settings.conf");
	string line;
	if (!nameFileout.is_open())
	{
		exit(0);
	}
	while (std::getline(nameFileout, line))
	{

		std::string s = line;
		std::string delimiter = "[Zoom]";

		size_t pos = 0;
		std::string token;
		while ((pos = s.find(delimiter)) != std::string::npos) {
			token = s.substr(0, pos);
			std::cout << token << std::endl;
			s.erase(0, pos + delimiter.length());

			stringstream convert(s);
			Z2 = atof(s.c_str());
		}


		AllocConsole();
		freopen("CONOUT$", "w", stdout);
		std::cout << s << std::endl;
	}
	nameFileout.close();

}

Output : 

Z2 = -10;

Settings.conf : 

[Zoom]-10

int main(int argc, char** argv) {



	//Initialize GLUT
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowSize(400, 400);

	//Create the window
	glutCreateWindow("Window");
	initRendering();

	GetSettings();
	AllocConsole();
	freopen("CONOUT$", "w", stdout);
	std::cout << Z2 << std::endl;

	//Set handler functions
	glutDisplayFunc(drawScene);
	glutKeyboardFunc(handleKeypress);

	glutReshapeFunc(handleResize);
	glutSpecialFunc(specialKeys);

	glutMainLoop();

}


Asokanta™ Working for freelance own project.If you want help or get information just send private message. ______________________________________________________________________________ All the links of Asokanta™ nick-name.ru/nickname/Asokanta/
MarcusAseth
MarcusAseth

@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?

Scouting Ninja
Scouting Ninja
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.

MarcusAseth
MarcusAseth

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

Scouting Ninja
Scouting Ninja
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.

h8CplusplusGuru
h8CplusplusGuru



#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();
}


Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.