global pointer in c language - variables

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

Related

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.

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

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;
}
}

Difference between value parameter and reference parameter?

Difference between value parameter and reference parameter ? This question is asked sometime by interviewers during my interviews. Can someone tell me the exact difference that is easy to explain with example? And is reference parameter and pointer parameter are same thing ?
Thanks
Changes to a value parameter are not visible to the caller (also called "pass by value").
Changes to a reference parameter are visible to the caller ("pass by reference").
C++ example:
void by_value(int n) { n = 42; }
void by_ref(int& n) { n = 42; }
void also_value(int const& n); // Even though a reference is used, this is
// semantically a value parameter---though there are implementation
// artifacts, like not being able to write "n = 42" (it's const) and object
// identity (&n here has different ramifications than for by_value above).
One use of pointers is to implement "reference" parameters without using a special reference concept, which some languages, such as C, don't have. (Of course you can also treat pointers as values themselves.)
The main difference is whether the object passed is copied. If it's a value parameter the compiler must generate such code that altering the function parameter inside the function has no effect on the original object passsed, so it will usually copy the object. In case of reference parameters the compiler must generate such code taht all operations are done on the original object being passed.
A pointer is a low-level way of representing a reference, so passing a pointer (by value) is how languages like C typically achieve pass by reference semantics.
The difference is pretty simple: direct parameters are passed by value, and the receiver receives a copy of what is passed; meaning that if the parameter is modified by the receiver, these changes will not be reflected back to the caller. (This is often called, appropriately enough, pass by value, or by copy.
There are basically three kinds of parameters; pointer, reference and direct.
The difference is pretty simple: direct parameters are passed by value, and the receiver receives a copy of what is passed; meaning that if the parameter is modified by the receiver, these changes will not be reflected back to the caller. (This is often called, appropriately enough, pass by value, or bycopy.
Pointers are also passed by value, but rather than sending the actual value, the caller sends the address of the value. This means that by following this pointer, the receiver can modify the argument. Note that changes made to the actual pointer still aren't reflected back to the caller.
The final form, call-by-reference, is sort of a middle ground between these two approaches. Essentially it can be thought of as a pointer that looks like a value.
It is worth mentioning that at the core of it all, parameters are always passed by value, but different languages have different ways of implementing reference semantics (see Kylotans answer).
// Example using C
// bycopy
int multiply(int x, int y) {
return x * y;
}
void multiply_p(int *x, int y) {
*x *= y;
}
int main () {
int i, j, k;
i = 20;
j = 10;
k = multiply(i,j); // k is now 200
multiply_p(&i, k); // i is now 4000 (200 * 20)
return 0;
}
Pseudocode:
Pass by Value:
void setTo4(value) { // value is passed by value
value = 4;
}
int x = 1;
setTo4(x);
// x is still 1
Pass by Reference:
void setTo4(value) { // value is passed by reference
value = 4;
}
int x = 1;
setTo4(x);
// x is 4

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.