View Full Version : how to use a global vars in QT?
wter27
20th January 2011, 15:44
Someone said you could write a static class and call it.
But I just wondered if I could use a global varieties to initialize my program.
Here is the code:
extern int var_name ;
void MainWindow::function_name_1()
{
int var_name;
var_name=1;
};
void MainWindow::function_name_2()
{
some_other_function(var_name);
};
The compiler says may be used uninitialized in this function.
So how to fix it?Anyone could give me some suggestions to use the global vars?
tbscope
21st January 2011, 04:36
Obviously, var_name is not initialized in the global scope.
What you did is create another var_name variable in function_name_1 and set it to 1. But that is a local variable that stops existing at the end of the scope (the } character).
You can remove
int var_name;
in the function function_name_1.
But, that means that function_name_1 MUST be called as the absolute first function at all times. Not very practical.
Note that you can initialize a variable directly like this:
int var_name = 1;
While you can use global variables without any problem, it is not in the style of C++ (object oriented) and it can easily lead to errors (which object uses the variable at which point in time? Is the value still correct? ...)
ChrisW67
21st January 2011, 04:48
Further, the code snippet:
extern int var_name ;
does not create a place to store an int. The extern keyword is used to specify that the variable is declared in a different file and that the linker will need to resolve this name.
FelixB
21st January 2011, 08:18
The compiler says may be used uninitialized in this function.
you have two functions. "function_name_1" initializes "var_name". "function_name_2" uses "var_name". What happens if you call "function_name_2" before you call "function_name_1"? - BINGO, you'd use an uninitialized variable, as the compiler said...
tbscope
21st January 2011, 08:54
What happens if you call "function_name_2" before you call "function_name_1"? - BINGO, you'd use an uninitialized variable, as the compiler said...
That doesn't even matter, even if function_name_1 is called before function_name_2, var_name is uninitialised.
FelixB
21st January 2011, 09:26
That doesn't even matter, even if function_name_1 is called before function_name_2, var_name is uninitialised.
oh, now I see. he redefines "var_name"...
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.