Difference between a "member variable" or "field" and a "global variable" - variables

What is the difference between a member variable or field and a global variable?Is the concept same ?

A member variable is declared within the scope of a class. Unless it’s static, there will be a different copy of the variable for every object of that class.
A global variable is declared outside the scope of any class and can be used from any function. There’s only one copy of it in the program.
Note that mainstream object-oriented languages distinguish between a global variable (which is declared outside the scope of any class or function) and a static local variable or class member. However, all the problems with global variables apply equally to mutable public data members that are accessible from anywhere in the program. For most purposes, you can think of these as the same thing.
Example Code
#include <iostream>
using std::cout;
using std::endl;
const int global_var = 1; // The definition of the global variable.
struct example_t {
public:
static int static_member_var; // A static member variable.
const static int const_static_member_var; // These are just declarations.
int member_var; // A non-static member variable.
// Every object of this type will have its own member_var, while all
// objects of this type will share their static members.
};
int example_t::static_member_var = 0;
const int example_t::const_static_member_var = global_var;
// We can use global_var here. Both of these exist only once in the
// program, and must have one definition. Outside the scope where we
// declared these, we must give their scope to refer to them.
int main(void)
{
example_t a, b; // Two different example_t structs.
a.member_var = 2;
b.member_var = 3; // These are different.
a.static_member_var = 5;
// This is another way to refer to it. Because b has the same variable, it
// changes it for both.
// We can use global_var from main(), too.
cout << "global_var is " << global_var
<< ", example_t::const_static_member_var is " << example_t::const_static_member_var
<< ", b.static_member_var is " << b.static_member_var
<< ", a.member_var is " << a.member_var
<< " and b.member_var is " << b.member_var
<< "." << endl;
return 0;
}

Global variables are any variables defined outside functions scope, they can be accessed anywhere in the program if they were defined outside of class scope, or they can only be accessed inside a class if they were defined inside the class's scope.
Local variables are any variables defined inside a function scope, they can only be accessed by that one function they were defined in.
Member variables are variables that are associated with a specific object of a class, they can only be declared inside a class's scope.
All member variables are global variables, but not all global variables are member variables.
Field is another term to describe variable. Similar to how method is another term to describe function, i.e. they mean the same thing, at least in Java :)
const int a = 0 // global variable, can be accessed from anywhere in the program
class Example {
int b; // member variable, also a global variable, can only be accessed inside this class
int fun () {
Foo c; // local variable, can only be accessed inside this method
return 0;
}
}

Related

Can I reuse same variable names if they're in different functions?

I'm making a program for the game 15 puzzle.
My function headers look like this:
void leftSlide(vector< vector<int> >& puzzle);
void rightSlide(vector< vector<int> >& puzzle);
void upSlide(vector< vector<int> >& puzzle);
void downSlide(vector< vector<int> >& puzzle);
my main function also has a vector< vector<int> > puzzle. Am I allowed to do this, or will this cause problems?
The scope of a variable is within the enclosing curly braces. For example,
void foo()
{
int x; // variable x is not known outside of foo
}
This scoping rule applies even for variables in the argument list. For example,
void boo (int y)
{
// variable y in not known outside of boo
}
Therefore, in your case, the variables will be passed from the main driver to the individual functions by reference. So, yes, you can have variables of the same name in different scopes.
simply yes
The potential scope of a variable introduced by a declaration in a block (compound statement) begins at the point of declaration and ends at the end of the block. Actual scope is the same as potential scope unless there is a nested block with a declaration that introduces identical name (in which case, the entire potential scope of the nested declaration is excluded from the scope of the outer declaration)

Programming Basics: Variable declaration, intitialiation, assignment, and scope

How does scope interact with variable declaration, initialisation, and assignment? The definition of those terms based on what I have learned so far is listed below:
Declaration: States the type of a variable, and it's name/identifier. Variables must have been declared before they can be assigned or read.
Assignment: Throws away the existing value of a variable and replaces it with a new one, the old value is thrown away at the end of the assignment statement, so the value can be incremented or otherwise adjusted, for example: x = x + y;
Initialisation: The name used for the first assignment of a variable, before initialisation, a variable has a default value, in the case of objects, those objects have a null value. Initialisation can be done in conjunction with declaration.
Scope: The "lifespan" of a variable, a variable is in scope until the end of the code block, at which point the memory used to store that variable is freed up. In effect, the variable is deleted or "killed", when the code block ends.
What I don't know is how scope interacts with Declaration and assignment. While the scope of a variable seems to be based solely on the code block in which it is Declared, I don't know how assignment interacts with scope. For example:
public class exampleClass
{
public static void main(String[] args) // using java for example
{
int x = 5; // x is declared here, and initialised with a value of 5
for (int i = 0; i < 10; i++) // i is declared and initialised here
{
x = i; // x is assigned the value of i each iteration
} // i goes out of scope here
System.out.println(x); // the value of x is printed
} // x goes out of scope here
}
In this example, x is declared and initialised (do we just say initialised?) in the main method, and is in scope for that method. However, x is assigned a value in the while loop. What will be printed when this code is executed, but more importantly why? Will it print "5", or "9"?
I have seen code throw up compiler exceptions because of syntax that would imply that x should print 5. However when I run this example code, I get "9".
One final question, why is it that multiple variables can be declared and initialised inline:
int x = 1, y = 4, z = 6;
But variables cannot be assigned inline:
x = 1, y = 4, z = 6;
The distinction between declaration and initialisation can be blurry; some languages make a clear distinction between these actions, in others initialisation is declaration. If a variable is initialised while it's being declared, it doesn't matter which you call it.
However, x is assigned a value in the while loop. What will be printed when this code is executed, but more importantly why? Will it print "5", or "9"?
9, because that's the last value that has been assigned to it before you print it.
Scope: The "lifespan" of a variable, a variable is in scope until the end of the code block, at which point the memory used to store that variable is freed up. In effect, the variable is deleted or "killed", when the code block ends.
Yes and no. Scope defines in what parts of code a particular variable is available. Different languages can have very different definitions of their scoping rules. A variable is typically garbage collected (in languages where that's applicable) when it goes out of scope, when no piece of code has any further access to it. In a simple function block, that happens when the function ends.
However, see this Javascript example:
function foo() {
var bar = 'baz';
return function () {
alert(bar);
};
}
The inner function which is returned from this function still holds a reference to bar. Even if foo ends, bar is being closed over by a closure and is still in scope within the inner function. As long as a reference to that returned function exists, bar still exists.

global pointer in c language

This is my friend question from my instructor about how to print
main method value of local variable in method function when it's
variable pushed and pop from stack (because when method function
called it's variable pushed and when it reached to end pop from
stack) then it's local variable storage back to the memory.
Why main method print 100 ?
// Define a global pointer
int *ptr;
int method()
{
// Define a variable local in this method
int local = 100;
// Set address of local variable (name of variable is local)
// in the ptr pointer
ptr = &local;
return -1;
}
int main()
{
// Call method
method();
// Print value of ptr pointer
cout<<*ptr<<"\n";
return -1;
}
If you are asking why the main method is printing 100.
1.The local variable is assigned some memory space. (say at X. Therefore [x]=>100)
2.The pointer which is global is then assigned to the point at X.(say pointers space is Y. [Y]=>X)
3.Therefore the point of the pointer is X.
4.Now you choose to print value of the pointer. i.e. [[y]]=[x] which is 100.
Why is doesn't print a garbage value is because even though the memory space is no longer allocated to local it still contains that value.
If you wrote some more code the point in memory might have been overwritten by another variable

Declaration of variables?

Case:1
class A
{
private int i=0;
public void display()
{
this.getValue();
}
private int getValue()
{
return i+2;
}
}
Case:2
class B
{
public void display()
{
int i=0;
this. getValue(i);
}
private int getValue(int i)
{
return i+2;
}
}
Does the declaration of "i" in both cases have any great
difference (other than the global access) whenever I call
display() ?
In this very case the effect is the same, but an instance of the class in the first snippet will occupy more memory.
Other than that in the first case it's a variable with the same address on each call and it retains the value, but in the second case it's not necessarily a variable with the same address - it is reallocated and reinitialized on each call.
Since you actually don't ever change i variable value you should declare it as const - this will give more clear code.
In first case i is a part of the object. When u create an object from class A, the object allocates memory for the variable "i". And it will remain until the object deleted.
But in the second way when you create the object from class B, there will be no memory allocation for the variable i. But only when you call the display function -in class B- memory variable "i" will be allocated temporarily. (When function's work is done all local variables will free)
In first case i exists outside of any method
In second case i exists only when display() method is called. If you want to give it persistence you can declare it as static.

What is the difference between a member variable and a local variable?

What is the difference between a member variable and a local variable?
Are they the same?
A local variable is the variable you declare in a function.
A member variable is the variable you declare in a class definiton.
A member variable is a member of a type and belongs to that type's state. A local variable is not a member of a type and represents local storage rather than the state of an instance of a given type.
This is all very abstract, however. Here is a C# example:
class Program
{
static void Main()
{
// This is a local variable. Its lifespan
// is determined by lexical scope.
Foo foo;
}
}
class Foo
{
// This is a member variable - a new instance
// of this variable will be created for each
// new instance of Foo. The lifespan of this
// variable is equal to the lifespan of "this"
// instance of Foo.
int bar;
}
There are two kinds of member variable: instance and static.
An instance variable lasts as long as the instance of the class. There will be one copy of it per instance.
A static variable lasts as long as the class. There is one copy of it for the entire class.
A local variable is declared in a method and only lasts until the method returns:
public class Example {
private int _instanceVariable = 1;
private static int _staticvariable = 2;
public void Method() {
int localVariable = 3;
}
}
// Somewhere else
Example e = new Example();
// e._instanceVariable will be 1
// e._staticVariable will be 2
// localVariable does not exist
e.Method(); // While executing, localVariable exists
// Afterwards, it's gone
public class Foo
{
private int _FooInt; // I am a member variable
public void Bar()
{
int barInt; // I am a local variable
//Bar() can see barInt and _FooInt
}
public void Baz()
{
//Baz() can only see _FooInt
}
}
A local variable is the variable you declare in a function.Its lifespan is on that Function only.
A member variable is the variable you declare in a class definition.Its lifespan is inside that class only.It is Global Variable.It can be access by any function inside that same class.
Variables declared within a method are "local variables"
Variables declared within the class not within any methods are "member variables"(global variables).
Variables declared within the class not within any methods and defined as static are "class variables".
A member variable belongs to an object... something which has state. A local variable just belongs to the symbol table of whatever scope you are in. However, they will be represented in memory much the same as the computer has no notion of a class... it just sees bits which represent instructions. Local variables and member variables can both be on the stack or heap.