473,786 Members | 2,578 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

static local variable in a member function.

Hi,

Can you solve the puzzle for me?

I have a main.cpp, testinclude.h, and test1.cpp and test2.cpp which include
testinclude.h
testinclude.h has a class Include defined. I always thought that the
compiler generates a copy of
class Include one each for test1.cpp and test2.cpp. But however they use the
same class definition for both test1.cpp and test2.cpp.

Following is the code.

//main.cpp
int NewMethod1();
int NewMethod2();
int main()
{
int i=NewMethod1();
i=NewMethod2(); // this function returns 1 where in i was expecting it to
return 2.
return i;
}

//testinclude.h
class Include
{
public:
Include(){}
int include1(int iN)
{
static int i = 0;
if(i == 0)
i = iN;
return i;
}
};

//test1.cpp
#include "testinclud e.h"
int NewMethod1()
{
Include inc;
int i = inc.include1(1) ;
return i;
}

//test2.cpp
#include "testinclud e.h"
int NewMethod2()
{
Include inc;
int i = inc.include1(2 );
return i;
}

Sep 27 '05 #1
3 4608
ishekara wrote:
Hi,

Can you solve the puzzle for me?
Try reading about static keyword.

I have a main.cpp, testinclude.h, and test1.cpp and test2.cpp which include
testinclude.h
testinclude.h has a class Include defined. I always thought that the
compiler generates a copy of
class Include one each for test1.cpp and test2.cpp. But however they use the
same class definition for both test1.cpp and test2.cpp.

There is always a single copy of the class. What the compiler generates
is multiple instances of the same class. So, you have mutiple objects
sharing the same code but having different instances of the data unless
the data is declared as static in which case they would all share the
same data member.
Following is the code.

//main.cpp
int NewMethod1();
int NewMethod2();
int main()
{
int i=NewMethod1();
i=NewMethod2(); // this function returns 1 where in i was expecting it to
return 2.
return i;
}

//testinclude.h
class Include
{
public:
Include(){}
int include1(int iN)
{
static int i = 0;
if(i == 0)
i = iN;
return i;
}
};

//test1.cpp
#include "testinclud e.h"
int NewMethod1()
{
Include inc;
int i = inc.include1(1) ;
return i;
}

//test2.cpp
#include "testinclud e.h"
int NewMethod2()
{
Include inc;
int i = inc.include1(2 );
return i;
}


Not sure why should you be expecting 2. i is a static variable which is
shared by all the instances of the class. It retains its value
in-between function calls. So, the first time you called include1(), i
got intialised to 1 and retained its value. The next call to include1()
still had i equal to 1, that is why 1 was returned and not 2. I am not
sure if you want i to be static. If you remove the static keyword, you
would get 2 as the return value.

Would advise you to read more on static.

Sep 27 '05 #2

"Jaspreet" <js***********@ gmail.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
ishekara wrote:
Hi,

Can you solve the puzzle for me?


Try reading about static keyword.

I have a main.cpp, testinclude.h, and test1.cpp and test2.cpp which
include
testinclude.h
testinclude.h has a class Include defined. I always thought that the
compiler generates a copy of
class Include one each for test1.cpp and test2.cpp. But however they use
the
same class definition for both test1.cpp and test2.cpp.


There is always a single copy of the class. What the compiler generates
is multiple instances of the same class. So, you have mutiple objects
sharing the same code but having different instances of the data unless
the data is declared as static in which case they would all share the
same data member.

I was thinking i should get different copies of the class. but i guess its
because
there are no different namespaces there is only one copy of the class in
global namespace.
Following is the code.

//main.cpp
int NewMethod1();
int NewMethod2();
int main()
{
int i=NewMethod1();
i=NewMethod2(); // this function returns 1 where in i was expecting it to
return 2.
return i;
}

//testinclude.h
class Include
{
public:
Include(){}
int include1(int iN)
{
static int i = 0;
if(i == 0)
i = iN;
return i;
}
};

//test1.cpp I tried to do the following change and was able to get different values
namespace test1
{ #include "testinclud e.h" }
using namespace test1; int NewMethod1()
{
Include inc;
int i = inc.include1(1) ;
return i;
}

//test2.cpp namespace test2
{ #include "testinclud e.h" }
using namespace test2; int NewMethod2()
{
Include inc;
int i = inc.include1(2 );
return i;
}


Not sure why should you be expecting 2. i is a static variable which is
shared by all the instances of the class. It retains its value
in-between function calls. So, the first time you called include1(), i
got intialised to 1 and retained its value. The next call to include1()
still had i equal to 1, that is why 1 was returned and not 2. I am not
sure if you want i to be static. If you remove the static keyword, you
would get 2 as the return value.

Would advise you to read more on static.

Thanks for help.
Sep 27 '05 #3
ishekara wrote:
Can you solve the puzzle for me?

I have a main.cpp, testinclude.h, and test1.cpp and test2.cpp which include
testinclude.h
testinclude.h has a class Include defined. I always thought that the
compiler generates a copy of
class Include one each for test1.cpp and test2.cpp. But however they use the
same class definition for both test1.cpp and test2.cpp.

Following is the code.

//main.cpp
int NewMethod1();
int NewMethod2();
int main()
{
int i=NewMethod1();
i=NewMethod2(); // this function returns 1 where in i was expecting it to
return 2.
Why did you expect it to return 2?
return i;
}

//testinclude.h
class Include
{
public:
Include(){}
int include1(int iN)
{
static int i = 0;
if(i == 0)
i = iN;
So, 'i' is only set to be equal to the argument value _iff_ its value is 0
at the time of call. Otherwise, its value is unchanged...
return i;
....and returned here.
}
};

//test1.cpp
#include "testinclud e.h"
int NewMethod1()
This function is called first, right?
{
Include inc;
int i = inc.include1(1) ;
Calling 'include1' with argument '1' causes the static data object 'i'
inside that member function to be set to 1 and returned, initialising
this local automatic 'i'...
return i;
....which in turn gets returned here.
}

//test2.cpp
#include "testinclud e.h"
int NewMethod2()
This function is called second, right?
{
Include inc;
int i = inc.include1(2 );
Calling 'include1' for a different object doesn't matter. The inner
variable 'i' of the 'Include::inclu de1' member function is the same
as before, and it already has the value 1. So, the passed argument
'2' is ignored and the value of the static data object 'i' is given
back to initialise this function's local 'i'. The value of it is '1'.
return i;
And it's returned here.
}


V
Sep 27 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
5397
by: IHateSuperman | last post by:
public class StaticField2{ public static void main(String args){ private int x, y; // <<== error 1 for ( y = 0 ; y < 100 ; y++){ x = StaticMethod(); System.out.println(" x = "+x); } } public static int StaticMethod(){ private static int m = 0; // <<== error 2
29
4413
by: Alexander Mahr | last post by:
Dear Newsgroup, I'm somehow confused with the usage of the static keyword. I can see two function of the keyword static in conjunction with a data member of a class. 1. The data member reffers in all objects of this class to the same data Or in other word by using the static keyword all objects of one class can share data. (This is what I want)
1
2035
by: Seb | last post by:
Is this efficient for a header file and a class? Does a 'static local' variable get created for each instance or include of the header file? Also, 'return _type().ToString();' does not seem to work. The error states: Object.h(16): error C2662: 'DataLib::Object::_type' : cannot convert 'this' pointer from 'const DataLib::Object' to 'DataLib::Object &' namespace DataLib
4
1877
by: Howard | last post by:
Hi, I came across some sample code for using a third-party API, and the code in it had several free-standing (i.e., non-member) functions, but strangely, these were declared as 'static'. My compiler tells me that the function has no prototype, which is weird, because there *is* a prototype in the header file. I was not able to find in my books any reference to a static function that was not a member function. The closest info I could...
16
2988
by: Eric | last post by:
I have a static class member variable as follows: struct A { static void Set (int i) { v = i; } static int& Get () { return v; } static int v; }; int A::v; // define A::v in the cpp file
5
2179
by: john | last post by:
By doing: void MyClass::MyFunction() { static int myvar; .... } We can defined a function local variable 'myvar' that keeps its value from call to call (the point is that the variable can not be easily
55
6249
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in C# in some way? Or maybe no, because it is similar to a global variable (with its scope restricted) which C# is dead against? Zytan
1
1733
by: rhd | last post by:
Hi, - C++ class with a private member function. - Private member function declares a static int locally with an initial value of 0 . - A single instance of the class is created. - The object calls the member function a number of times, each time the local variable is incremented. - Eventually the object calling the member function is deleted.
3
1796
by: Bryan Parkoff | last post by:
The local variables and local functions are inside class body. You define a variable to the class "Reg reg;" in the main function. The reg variable has a pointer. The pointer gives memory address. The memory address accesses local variable and local function. It is fine design according to your preferance. I try to remove a pointer so I let local variable and local function as global to access to the memory directly without needing a...
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9496
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10363
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9961
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7512
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6745
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3669
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.