Read Only Variable Assignment? - c++

I have a private member variable called "Probes", Within one of my private member functions, i want to use the variable "Probes" to keep track of the number of comparisons made. To do this I just put the variable within the loop and did Probes++ each time through. But when I compile and run it, it says that I cannot assign to a read only variable? How can I correct this?

If this is a read only variable (constant) you cannot do Probes++ (which is similar to Probes = Probes + 1) because constants cannot be updated. What you can do is to declare it as a variable (which you can modify while the program is executed) or just declare Probes as mutable.

Related

Declaring static and non-static variables inside loops

I want to use a variable inside a loop, but I don't want it to be re-declared on every iteration. Obviously I can declare it outside of the loop but I wondered what would happen if I declared it as static inside the loop.
To test this I declared both a static and a non-static variable inside a while loop and printed their memory addresses on each iteration. I expected the address of the non-static variable to keep changing and that of the static to stay the same.
while (true)
{
int var1;
static int var2;
cout << &var1 << "\n"
<< &var2 << endl;
}
Results: To my surprise the addresses of both variables stayed the same.
Is this some kind of compiler optimization or was I wrong to assume that re-declaring the non-static variable should yield a different address on every iteration? I'm using gcc 9.3.0 with no optimization flags.
Is the static variable a good alternative to declaring a non-static variable outside of the loop (assuming I won't need it in the outer scope and I'm not concerned that the variable will retain its last value in case the loop is entered again at a later time)?
The non-static variable gets created and destroyed on each iteration of the loop.
It just so happens that it gets created, every time, on the same memory address.
However, relying on this, and relying on the variable's contents getting preserved across loop iterations will be undefined behavior.
Expecting the compiler to change the address of the local variable is not reasonable: there is only a limited number of possible addresses (264) but your loop is infinite, so the address would have to repeat somehow. And the easiest way to repeat is to repeat immediately.
Regarding whether static is good enough - depends on the usage. However, static is probably not better than local for most usages, otherwise static would be the default behavior.
The static variable obviously only gets initialized once so it is perfectly reasonable to expect the address to stay the same.
Now, for the non-static variable. When a variable is declared inside a loop, it will be destroyed before the next iteration of the loop. This means that the memory will be available again the next time the loop runs. Therefore, the variable would likely have the same address.
In fact, the compiler probably has to do this because it has no way of knowing how many times the loop will run. Since computers only have finite memory, we cannot allocate a new variable at each iteration.
One way to think about it is that the variable is actually created outside the loop. In fact, some languages (e.g. Pascal) actually require you to declare all variables at the beginning of a function. It's just that declaring variables inside loops reduce the cognitive load a bit which is why most languages support it. But in the end, it all comes down to the same thing.

Difference between static data member and global variable

Variations of this question might have been asked earlier as well. This question is about static data member vs global variable not static variable vs global variable.
All of us know what static data member and global variables do. How compilers link them, where they get mapped in memory layout, their default values etc. When I think about them I do not have a clear picture of the possible scenarios where we should use static data member instead of global variable.
I thought of one use case where you want to count the number of objects created for a class. You make one static data member and increase in the ctor whenever you create an new object. But at same thought, we could also do the same thing, counting of the created objects, with the global variable as well.
So, it is not clear to me till now that what are the use cases of using static data member vs global variable?
They are in different scopes:
The static data member can have visibility restriction public/protected/private.
The global variable can be modified without restriction
The static (global) variable can only be modified in file scope.

when a ttcn function "runs on SomeComponent", how can it access the instance of this SomeCOmponent type?

I read that when ttcn function is annotated with "runs on SomeComponent", it means that when it is called, it gets passed an instance of that SomeComponent. How can this function access this instance? Is it available in some special variable?
Inside the function, you can use all variables defined in SomeComponent as if they are local variables defined in the function.
The only difference between these variables and local variables is that their lifetime and scope is larger than local's. Their values are accessible in all functions that run on that component and they are initialised on component startup.
As Nomce said, the instance variables of a component are available in the same scope as local variables (mixing dynamic and static scoping).
But sometimes you need the actual component reference - in case you need to pass it around, do mappings or connection (store in array and - generally - perform dynamic configuration). Then you can use the special self reference.

Copy static class member to local variable for optimization

While browsing open source code (from OpenCV), I came across the following type of code inside a method:
// copy class member to local variable for optimization
int foo = _foo; //where _foo is a class member
for (...) //a heavy loop that makes use of foo
From another question on SO I've concluded that the answer to whether or not this actually needs to be done or is done automatically by the compiler may be compiler/setting dependent.
My question is if it would make any difference if _foo were a static class member? Would there still be a point in this manual optimization, or is accessing a static class member no more 'expensive' than accessing a local variable?
P.S. - I'm asking out of curiosity, not to solve a specific problem.
Accessing a property means de-referencing the object, in order to access it.
As the property may change during the execution (read threads), the compiler will read the value from memory each time the value is accessed.
Using a local variable will allow the compiler to use a register for the value, as it can safely assume the value won't change from the outside. This way, the value is read only once from memory.
About your question concerning the static member, it's the same, as it can also be changed by another thread, for instance. The compiler will also need to read the value each time from memory.
I think a local variable is more likely to participate in some optimization, precisely because it is local to the function: this fact can be used by the compiler, for example if it sees that nobody modifies the local variable, then the compiler may load it once, and use it in every iteration.
In case of member data, the compiler may have to work more to conclude that nobody modifies the member. Think about multi-threaded application, and note that the memory model in C++11 is multi-threaded, which means some other thread might modify the member, so the compiler may not conclude that nobody modifies it, in consequence it has to emit code for load member for every expression which uses it, possibly multiple times in a single iteration, in order to work with the updated value of the member.
In this example the the _foo will be copied into new local variable. so both cases the same.
Statis values are like any other variable. its just stored in different memory segment dedicated for static memory.
Reading a static class member is effectively like reading a global variable. They both have a fixed address. Reading a non-static one means first reading the this-pointer, adding an offset to the result and then reading that address. In other words, reading a non-static one requires more steps and memory accesses.

Should I set global vars value on startup or the first time I use them? C++

I have a few global vars I need to set the value to, should I set it into the main/winmain function? or should I set it the first time I use each var?
Instead, how about not using global variables at all?
Pass the variables as function parameters to the functions that need them, or store pointers or references to them as members of classes that use them.
Is there a chance that you won't be using the global var? Is calculating any of them expensive? If so then you have a argument for lazy initialization. If they are quick to calculate or always going to be used then init them on startup. There is no reason not to, and you will save yourself the head ache of having to check for initialization every time you use it.
When the linker links your program together, global variables (also known as writable static data) are assigned to their own section of memory (the ELF .data section) and have a value pre-assigned to them. This will mean that the compiler will not need to generate instructions to initialize them. If you initialize them in the main function, the compiler will generate initialization instructions unless it is clever enough to optimize them out.
This is certainly true for ELF file formats, I am not sure about other executable formats.