I have some global variables in my program and I tried to avoid them but I don't know how..
Here is my program:
Here
Is there any alternative to avoid those variables?
And any other remark is appriciated too
I think you have multiple possibilities.
Create a class and put your functions and your global variables inside (preferred way)
If you just care about name conflicts you can use unnamed namespaces
It your global variable is used in only one function, declare it as a static variable inside that function (its value will be kept between calls)
What about to use a STATIC for i_mouse and depthimagemouse inside the function onMouse (you use it in just 1 function) and a #define for the constant variables?
I think it can be a good solution in your case.
Related
This is probably a pretty straight forward question but for some reason I haven't been able to find an answer on the great interwebs so far.
When using global variables, I know global variables are bad and should for the most part be avoided, but on those rare occasions where a global variable gets the job done best, should the global variable be both declared and initialized at once? I have been recently trying to drill into my head the mantra "always initialize variables upon declaration when possible" since this usually saves many headaches later and is encouraged with C++. Does this rule apply to global variables as well though?
If you initialize a variable in its global scope when declaring it, how does this affect the program? Is this best practice?
You're advice is very much appreciated!
You want to initialize variables at the point they are declared whenever possible, regardless of their scope.
For global variables, if you don't initialize them when they are declared, you need to initialize them after your program starts running, which leaves open the possibility that the global will be used before this occurs. Classes, with constructors, will be default constructed, which can cause work to be done and thrown out when the variable is assigned its proper value.
Global variables have another problem: the order they are constructed/initialized is only partially defined by the language. If you have two global variables that are declared in different source modules, you do not know which one will be constructed first. This can lead to the static initialization order fiasco.
So you can run into problems if you initialize them, or different problems if you don't. This is one reason why global variables should be avoided.
What is the solution? You can wrap your global variables into an accessor function. This will ensure that the variable has been properly initialized. So rather than the plain declaration:
SomeType big = ReadBig();
you can place it into a function:
const SomeType &GetBig() {
static SomeType big = ReadBig();
return big;
}
This also has the advantage of having your global variable const, so that it cannot be changed if this is necessary.
Yes, you do want to initialize global variables. As #paladin commented, if you do not initialize them, the compiler will attempt to initialize them with the default values.
Consider this simple example:
struct Foo {
Foo(int x, char *y, double z) {}
};
Foo f;
The compiler will try to initialize f, but there is no default constructor. This configures an error:
<source>:5:5: error: no matching constructor for initialization of 'Foo'
Foo f;
^
<source>:1:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
So yes, you need to initialize your global variables, and if you don't the compiler will try to do it for you.
Sorry, forgot, was it possible to declare but not define local (inside function) variable in C/C++?
Looks like it is not possible, since it is impossible to access local variable from somewhere else, except this function.
Then, what is it correct to say: variable should be "declared" before use or "defined" before use?
Sorry, forgot, was it possible to declare but not define local (inside function) variable in C/C++?
No, local (block-scope) variables only have declarations. They are instantiated when the program reaches the declaration, with no need for a separate definition to control instantiation.
Then, what is it correct to say: variable should be "declared" before use or "defined" before use?
Variables, and named entities in general, must be declared before use. Not all variables have separate definitions; if they do, then the definition doesn't usually need to be available to use the variable.
Global (namespace-scope) and static member variables (depending on use) need definitions, to determine which translation unit is responsible for instantiating them. Global variables can also be declared separately from their definition, in their namespace or in functions inside that namespace.
For local variables, there is no concept of definition. They are just declared and are conditionally instantiated according to the flow of program.
Separate declaration and definition are used for global variables and functions.
I was reading through C++ Primer 5th Edition, and was confused as to why it's possible to use a constexpr pointer on variables defined outside of a function but not declared outside a function.
Is there any times when you would define outside of a function? It seems you often will declare outside of functions when using extern, but I'm not sure how often one would define variables outside a function (unless main doesn't count as a function in this case).
EDIT: Emphasis mine
For reasons we'll cover... variables defined inside a function are not stored at a fixed address. Hence, we cannot use a constexpr point to such variables. On the other hand, the address of an object defined outside of any function is a constant expression and so may be used to initialize a constexpr pointer.
There are situations that I have to choose local classes over lambda when overloading operator() is not enough or when I need virtual functions or something else.
um.. for example:
I need a object that captures local variables, and holds more than one functions, which are, unfortunately of same signature.
Overloading lambdas can solve such problem if the functions are of different signatures. And I think this is one common problem since there is the lambda-overloading trick.
I need a object that capture local variables and inherits some other class or have member variables.
This is something happens everyday in the java world. Dynamic polymorphism has its usefulness, at least sometimes.
What I'm doing now, is defining some helper macros like these:
#define CAPTURE_VAL(Var) decltype(Var) Var
#define CAPTURE_REF(Var) decltype(Var) &Var
#define INIT_CAPTURE(Var) Var(Var)
And put them into the local class:
struct Closure
{
Closure(CAPTURE_VAL(var1), CAPTURE_REF(var2)) : INIT_CAPTURE(var1), INIT_CAPTURE(var2)
{
}
int foo()
{
return some_expression;
}
private:
CAPTURE_VAL(var1);
CAPTURE_REF(var2);
} closure(var1, var2);
And this is ugly.
I have to refer a same variable three times.
I have to give the class a name for ctor.
I have to give a variable name for the closure, though I think this cannot be helped under the current standard.
At least in VC++11, captured variables of a lambda are private, so I cannot simply inherit the lambda class. And inheriting lambda class, at least in VC++11, needs a variable (or maybe some other placeholders for the evaluation) for the lambda, which is ugly.
And I think I don't even know if the standard allows me to capture the type of local variables in a local class this way...
Tested on GCC 4.6, local variable's type can't be captured as in VC++. And captured variables are not exposed as in VC++. LOL
Ah, my bad. I forgot to turn C++11 on. This works fine on G++. But lambda types can't be inherited, and captured variables are still not exposed.
Not quite fine... Have to leave -fpermissive on. Or G++ think the member variables conflict with local variables used in decltype().
I've been wandering why C++ has chosen such a high-leveled lambda for closure instead of more generic local class that can capture local variables.
This is going to be more than fits into a simple comment on your question, so I'll make it an answer.
There are indeed cases where you want something else and more complex than a simple functor or lambda. But these cases are very different and diverse, there is no "one fits all" solution, especially none that fits into a few lines and that will not blow the scope of a single function.
Creating complex behavior on the fly locally inside a function is not a good idea in terms of readability and simplicity, and most surely will violate the SRP for the function.
In many cases, if you have to write more than a single operator(), that means you will want to reuse the code you have written, which cannot be done if it is inside a local class.
Meaning: In most cases it will be the best solution to write a proper class, outside the function, with proper constructors and so on.
I have a requirement where a (const) variable should be available throughout an entire cpp which consists of several classes. I have decided to use a namespace to solve the problem, but unsure about the following:
Do I need to define this variable as static?
Is it true that I can avoid making the variable static only if I go with an unnamed namespace?
You don't need to define the variable as static, or in an anonymous namespace. However, if you're not using this object outside of the file it's defined in, it's a good idea, to reduce namespace pollution and speed up links (by reducing how many symbols need to be considered by the linker).
If you declare a variable in an anonymous namespace, it will be effectively static. There's no need to actually make it static as well (although you can if you like). The advantage of anonymous namespaces is you can also define types (classes, structs, enums, typedefs) as well as static variables and functions.