Is there a such thing as a "Global Variable" in C++?

Started by
13 comments, last by Janju 18 years, 9 months ago
I don't understand, is there anything with my advices?
Advertisement
Theres even another option for the original poster.

He wants to call a function and have it able to change the original variables value. Sounds like a job for a reference to me.

main.cpp:#include <iostream>#include "otherfile.h"int main(){  int myint = 1;  myfunc(myint);  std::cout << "My Int : " << myint << std::endl;}otherfile.h:#ifndef OTHERFILE_H#define OTHERFILE_Hvoid myfunc(int &p_int);#endifotherfile.cpp:#include "otherfile.h"void myfunc(int &p_int){  p_int = 42;}


And of course there is ANOTHER option, which is to make the function return the modified value:

main.cpp:#include <iostream>#include "otherfile.h"int main(){  int myint = 1;  myint = myfunc(myint);  std::cout << "My Int : " << myint << std::endl;}otherfile.h:#ifndef OTHERFILE_H#define OTHERFILE_Hint myfunc(int p_int);#endifotherfile.cpp:#include "otherfile.h"int myfunc(int p_int){  if(p_int == 1)    p_int = 42;  else    p_int = 99;  return p_int;}


I would investigate all these options (mine and the others) before using a global.
Ok, if I want to use it in lets say..Main.cpp and have 1 header file and use a global string, how would it be done?? I tried what you all said but I'm geting tons of errors!
The best thing to do is just choose whatever you think you'd prefer, and go for it. -Promit
Quote:Original post by orcfan32
Ok, if I want to use it in lets say..Main.cpp and have 1 header file and use a global string, how would it be done?? I tried what you all said but I'm geting tons of errors!


Well, you know, it's really hard to help you with your problems if you refuse to post code. Maybe if you post the code snippets that you added to try to do what we recommended we could help you out with the errors instead of giving you the answer. You see, the whole point in asking questions is to learn. If we just post all your code for you, and you copy it into your project, what are you learning?

Instead, post the code snippets that relate to the problem (like I did) and what errors you are getting, and we can help you figure those out.
I use static variables in classes for stuff like this most of the time:
// .hclass global{public:   static int important_counter;}// .cppint global::important_counter = 0;

This topic is closed to new replies.

Advertisement