Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: save variable value for next call of the function

Is there a way to initialize a variable in a function and save its value for next call of function?

I'm making application in qt and i have one function connected with a signal. I want an variable in that function to change after the other one reaches its goal. Here is the body of that function:

void objekt::advance(int phase)
{
if(!phase) return;

QPointF location = this->pos();
if (int(location.x())==200 || int(location.x())==-200)
{
    smijer=-smijer;

}
setPos(mapToParent(smijer,0));
}

I defined the smijer variable as static int. But i dont'know how to initialize it only once, when program starts, and how to keep its new value after each call of the function.

like image 546
speedyTeh Avatar asked May 20 '13 00:05

speedyTeh


2 Answers

Your answer is in your question basically. Static variables (either a class member or local variable of a function) is initialized only once where it is terminated. For example;

#include <iostream>
int foo () {
   static int sVar = 5;
   sVar++;
   return sVar;
}

using namespace std;
int main () {
   int iter = 0;
   do {
       cout << "Svar :" foo() << endl;
       iter++;
      }while (iter < 3); 
} 

if you write a program like that it will print out Svar values just like;

Svar :6
Svar :7
Svar :8

So as you see although we call foo function three times the initialization of a static varible is done only once.

like image 60
mecid Avatar answered Sep 27 '22 17:09

mecid


Why am I being downvoted? He wants to change a variable and preserve the states after function calls. (He doesn't specify whether the variable is a member of the class or anything, so I'm assuming it's not. I'll change my answer if he clarifies and states his question less ambiguously.)

You're going about this wrong. To keep a variable after a function's scope ends, you have to allocate it on the heap rather than the stack. You can use new or malloc to do this, but you also have to free this memory with delete and free, in that order.

With new and delete:

#include <iostream>

void modify(int * p){
    (*p)++;
}

int main(void){
    int * pointer = new int;
    *pointer = 5;

    std::cout << *pointer << std::endl;

    modify(pointer);

    std::cout << *pointer << std::endl;

    delete pointer;
    return 0;
}

And with malloc and free:

#include <iostream>
#include <cstdlib>

void modify(int * p){
    (*p)++;
}

int main(void){
    int * pointer = (int*)malloc(sizeof(int)); //DO NOT CAST IN C
    *pointer = 5;

    std::cout << *pointer << std::endl;

    modify(pointer);

    std::cout << *pointer << std::endl;

    free(pointer);
    return 0;     
}

new does provide facilities for deleting arrays quickly and is better overall for normal use C++.

like image 30
GRAYgoose124 Avatar answered Sep 27 '22 16:09

GRAYgoose124