I have a question regarding C++. So I have made this program, that computes all possible combinations to solve a problem using recursion(instead of 9 loops). This is a part of the code:
int used[9];
nMin=1000;
void Combinations(int index)
{
if(index>8)
{
return;
}
for(int i=k;i<4;i++)
{
used[index]=i;
if (sum<nMin && Check())//Checks the solution
{
nMin = sum;
used[i]=0;
return;
}
else
{
Combinations(index+1);
}
}
}
The for loop, that should repeat 4 times resets every time recursive call returns. In other words the loop variable is set to 0. Is that just how it works, and do I have to store current loop variable value, or is there another way.
Edit: thank you guys, for detailed information and your answers. The code worked after a few tweaks.
If I am reading this correctly, your question is whether the loop variable i will be protected/preserved by the recursive calls to Combinations.
The answer is yes, the value of the loop counter will be preserved. The reason is scope. Each time the function is called, the stack creates space for a new variable i scoped to the current call. This means all interactions with i during a function call are with the i created for that specific call.
Note: The C/C++ language standards have no explicit notion of a stack. This is actually an implementation detail for the implementation of automatic storage.
int i is a local variable that exists within the context of that for loop for that instance of that function call. When you make a recursive call to the same function, you're pushing a brand new instance of that function call on the stack, which has its own for loop with its own int i variable. They are in no way connected to each other.
If you want all recursive calls to the function to share a counter, you will need to define it as a static variable, and define it outside of the scope of the for loop, like this:
void Combinations(int index)
{
static int persistentCounter;
This will maintain it's value in recursive calls.
Related
I'm writing an Object Oriented version of FCFS scheduling algorithm, and I've hit a problem. I need to know if there's any way to access an array of objects inside the member function definition, without passing it as a parameter explicitly.
I've tried using "this-pointer", but since the calculation of finish time of current process requires the finish time of the previous, "this" won't work. Or at least I think it won't. I have no idea how to access "previous" object using "this"
void Process :: scheduleProcess(int pid) {
if(pid == 0) finishTime = burstTime;
else finishTime = burstTime +
this->[pid-1].finishTime;
turnAroundTime = finishTime - arrivalTime;
waitingTime = turnAroundTime - burstTime;
}
I can obviously send the array of objects as a parameter and use it directly. I just want to know if there's a better way to do this:
This is the part that's calling the aforementioned function:
for(int clockTime = 0; clockTime <= maxArrivalTime(process);
clockTime++) {
// If clockTime occurs in arrivalTime, return pid of that
process
int pid = arrivalTimeOf(clockTime, process);
if(pid >= 0) {
process[pid].scheduleProcess(pid);
} else continue;
}
Since I'm calling scheduleProcess() using process[pid], which is a vector of objects, I should be able to manipulate the variables pertaining to process[pid] object. How do I access process[pid-1] in the function itself? (Without passing process vector as an argument)
Since scheduleProcess is a member of Process, it only knows what the Process object knows. The previous process is unknown at this level. There are ways that use Undefined Behavior and make more assumptions about your code to get around this, but these should be avoided.
One portable solution to avoid all that is to simply pass in the previous process's finish time as a parameter, since you know this value at the point of the call to scheduleProcess. Where there is not a previous process (the first entry in the array), this finish time would be 0.
I wonder, is the marked line in the below code correct. Because in this line the result of the function is assigned to the static variable prevRecCallResult (I'll call it "plain assignment"), which is changed inside this function (I'll call it "inside assignment").
Is it guaranteed, that the "inside assignment" is done, when the "plain assignment" executes?
int f(int _n)
{
if (_n >= 1)
{
static int prevRecCallResult;
prevRecCallResult = f(_n - 1); //<-- Is this line Ok?
return prevRecCallResult + 1;
}
else
return _n;
}
I know, the standard says, that a sequence point occurs:
At a function return, after the return value is copied into the
calling context.
, but I'm not sure, this is the answer to my question.
Update:
Considering replies I've received, I should clarify my question:
It's essence is: Is it true, that the prevRecCallResult is not in use by the assignment expression (in marked line) (i.e. is not occupied by it) until f(_n - 1) is finished? (And thus, until this moment, prevRecCallResult is absolutely free for any assignments inside f(_n - 1)?)
static int prevRecCallResult;
prevRecCallResult = f(_n - 1); //<-- Is this line Ok?
Your code is perfectly OK. But just wanted to make you remember that static int prevRecCallResult; executes only once. But prevRecCallResult = f(_n - 1); is assigned after each function call. Once function return prevRecCallResult's at time function's return value will be used in rest of the function.
One more thing, static variable will not die, after you return from function. So prevRecCallResult will not die across function calls.
As I remember all static variables as well as all global variables in C and C++ are assigned automatically to default value for their types - in this particular example default value for 'static int prevRecCallResult' will be 0. So your fears are unfounded (you can easily check this with debugger).
At the same time I cannot understand why you use static variable in this code... is it just simplified code for question or is it real code where you trying to economize memory on automatic variable of recursive function?
I've found a question sorta similar to this one, though put in a more complex way than I think I require (received a -2 for question score). Hopefully this will be easier to follow.
The general gist of things is the two classes involved are GUI and Player (I've had the same problem elsewhere with other classes, but if I can understand why this one isn't working, it should apply to the rest).
GUI includes "Player.h". The class Player has a public boolean variable 'hasBall'; When a 'Player' is passed into a function Pass() and the boolean value changed, it seems that it is only a temp object thus isn't updating the object being passed itself. See code below:
This works fine, boolean values for Plyr1A and Plyr2A (defined in Gui.h) are changed and preserved
Plyr1A.hasBall = false;
Plyr2A.hasBall = true;
However boolean values for Plyr1A and Plyr2A remain the same with this.
Pass(Plyr1A,Plyr2A); //Boolean values for Plyr1A and Plyr2A remain the same with this.
void GUI::Pass(Player passer, Player receiver) {
passer.hasBall = false;
receiver.hasBall = true;
}
If anyone could explain to me why this occurs I'd be rather thankful! If there is any extra information needed please let me know.
Cheers :)
Your function makes a copy of the arguments (they are passed by value), then changes the copy, not the "original" objects(in the body of the function).
You should change it to take pointers or references, for example:
//-------------------v---------------v <---these are references
void GUI::Pass(Player& passer, Player& receiver) {
Of course, you should change the declaration, too.
Use references to pass your objects.
Consider this function:
void someFunction (int j)
{
j = 8;
}
And say we call it like this:
someFunction (3);
Are you thinking the assignment in someFunction somehow makes that 3 become an 8? Your expectation makes no sense. Without some kind of special arrangement, it cannot be that an assignment inside a function changes values in the caller.
I have some small helper functions needed throughout the code.
To work, they need to be initialized with some data once.
Where should I store the init data?
I've come up with two methods:
I create static variables in the scope of the helper.cpp file which I set with a dedicated setter function and then use in my helper function.
static int _initData = 0;
void initHelpMe(int initData)
{
_initData = initData;
}
void helpMe()
{
doSomethingWith(_initData);
}
Or I use a static function variable inside the original helper function and a default parameter to it.
void helpMe(int initData = 0)
{
static int _initData = 0;
if (initData != 0)
_initData = initData;
doSomethingWith(_initData);
}
(Lets asume that 0 is outside of the valid data range of initData and that I've not shown additional code to ensure an error is raised when the function is called for the first time without initiating it first.)
What are the advantages / disadvantages of those two methods and is there an even better way of doing it?
I of course like the second method, because it keeps all the functionality in one place. But I already know it is not thread-safe (which is not an issue a.t.m.).
And, to make this more interesting, albeit being C++ this is not to be used in object-oriented but in procedural code. So please no answers proposing objects or classes. Just imagine it to be C with the syntax of C++.
I was going to suggest that you wrap your data into an object, until I realized that you are asking for a C solution with a C++ tag...
Both of your solutions have their benefits.
The second one is the one I'd prefer, assuming we just go by "what it looks like/maintainability". However, there is a drawback if helpMe is called MANY times with initData == 0, because of the extra if, which isn't present in the first case. This may or may not be an issue if doSomethingWith() is long enough a function and/or the compiler has the ability to inline helpMe (and initData is constant).
And of course, something in the code will have to call initHelpMe too, so it may turn out to be the same anyway.
In summary: Prefer the second one, based on isolation/encapsulation.
I clearly prefer the second! Global static data in different compilation units are initialized in unspecified order (In one unit in order, though). Local static data of a function is initialized at first call.
Example:
If you have two translation units A and B. The unit A calls during initialization the function helpMe of unit B. Assume the order of initialization is A, B.
The first solution will set the zero initialized _initData to some initData. After that the initialization of unit B resets _initData back to zero and may produce a memory leak or other harm.
There is a third solution:
void helpMe(int initData = 0)
{
static std::once_flag once;
static int _initData = 0;
std::call_once(once, [&] {
_initData = initData;
}
doSomethingWith(_initData);
}
I feel strongly both ways.
Prefer option 2 for the isolation, but option 1 lends itself to porting to a C++ class. I've coded both ways. It comes down to the SW architecture.
Let me offer another point.
Both options down side: You have not limited initialization to one occurrence. "need to be initialized with some data once". It appears OP's conditions insure a proper initialization of initHelpMe(123) or HelpMe(123) followed by helpMe(), but do not prevent/detect a secondary initialization.
Should a secondary need to be prevented/detected, some additional code could be used.
// Initialization
if (_initData != 0) {
; // Handle error
}
_initData = initData;
Another paradigm I've used follows. It may not be realizable in you code as it does not pass initData as a parameter but magically can get it.
void helpMe(void) {
static int Initialized = 0;
if (!Initialized) {
Initialized = 1;
_initData = initData();
}
doSomethingWith(_initData);
}
Let's say you have a function in C/C++, that behaves a certain way the first time it runs. And then, all other times it behaves another way (see below for example). After it runs the first time, the if statement becomes redundant and could be optimized away if speed is important. Is there any way to make this optimization?
bool val = true;
void function1() {
if (val == true) {
// do something
val = false;
}
else {
// do other stuff, val is never set to true again
}
}
gcc has a builtin function that let you inform the implementation about branch prediction:
__builtin_expect
http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
For example in your case:
bool val = true;
void function1()
{
if (__builtin_expect(val, 0)) {
// do something
val = false;
}
else {
// do other stuff, val is never set to true again
}
}
You should only make the change if you're certain that it truly is a bottleneck. With branch-prediction, the if statement is probably instant, since it's a very predictable pattern.
That said, you can use callbacks:
#include <iostream>
using namespace std;
typedef void (*FunPtr) (void);
FunPtr method;
void subsequentRun()
{
std::cout << "subsequent call" << std::endl;
}
void firstRun()
{
std::cout << "first run" << std::endl;
method = subsequentRun;
}
int main()
{
method = firstRun;
method();
method();
method();
}
produces the output:
first run subsequent call subsequent call
You could use a function pointer but then it will require an indirect call in any case:
void (*yourFunction)(void) = &firstCall;
void firstCall() {
..
yourFunction = &otherCalls;
}
void otherCalls() {
..
}
void main()
{
yourFunction();
}
One possible method is to compile two different versions of the function (this can be done from a single function in the source with templates), and use a function pointer or object to decide at runtime. However, the pointer overhead will likely outweigh any potential gains unless your function is really expensive.
You could use a static member variable instead of a global variable..
Or, if the code you're running the first time changes something for all future uses (eg, opening a file?), you could use that change as a check to determine whether or not to run the code (ie, check if the file is open). This would save you the extra variable. Also, it might help with error checking - if for some reason the initial change is be unchanged by another operation (eg, the file is on removable media that is removed improperly), your check could try to re-do the change.
A compiler can only optimize what is known at compile time.
In your case, the value of val is only known at runtime, so it can't be optimized.
The if test is very quick, you shouldn't worry about optimizing it.
If you'd like to make the code a little bit cleaner you could make the variable local to the function using static:
void function() {
static bool firstRun = true;
if (firstRun) {
firstRun = false;
...
}
else {
...
}
}
On entering the function for the first time, firstRun would be true, and it would persist so each time the function is called, the firstRun variable will be the same instance as the ones before it (and will be false each subsequent time).
This could be used well with #ouah's solution.
Compilers like g++ (and I'm sure msvc) support generating profile data upon a first run, then using that data to better guess what branches are most likely to be followed, and optimizing accordingly. If you're using gcc, look at the -fprofile-generate option.
The expected behavior is that the compiler will optimize that if statement such that the else will be ordered first, thus avoiding the jmp operation on all your subsequent calls, making it pretty much as fast as if it wern't there, especially if you return somewhere in that else (thus avoiding having to jump past the 'if' statements)
One way to make this optimization is to split the function in two. Instead of:
void function1()
{
if (val == true) {
// do something
val = false;
} else {
// do other stuff
}
}
Do this:
void function1()
{
// do something
}
void function2()
{
// do other stuff
}
One thing you can do is put the logic into the constructor of an object, which is then defined static. If such a static object occurs in a block scope, the constructor is run the fist time that an execution of that scope takes place. The once-only check is emitted by the compiler.
You can also put static objects at file scope, and then they are initialized before main is called.
I'm giving this answer because perhaps you're not making effective use of C++ classes.
(Regarding C/C++, there is no such language. There is C and there is C++. Are you working in C that has to also compile as C++ (sometimes called, unofficially, "Clean C"), or are you really working in C++?)
What is "Clean C" and how does it differ from standard C?
To remain compiler INDEPENDENT you can code the parts of if() in one function and else{} in another. almost all compilers optimize the if() else{} - so, once the most LIKELY being the else{} - hence code the occasional executable code in if() and the rest in a separate function that's called in else