Declare a global object inside of a function (c++) [duplicate] - c++

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 7 years ago.
I'm declaring objects of a struct inside of a function and i'd like to access said objects outside of that function (making them global). Here's an example of what i'd like to do
#include <iostream>
using namespace std;
struct exampleStruct
{
int ID;
};
void makeExampleStruct ()
{
exampleStruct exampleObj[30];
for (int r=0;r<=30;r++)
{
exampleObj[r].ID=r;
}
}
int main()
{
makeExampleStruct();
cout << exampleObj[1].ID << endl;
return 0;
}
This gives me a "'exampleObj' was not declared in this scope". I know i could simply declare the objects creation inside of main, but i'd rather keep it inside of a function so it's easier to read. Is there a way of doing that?
Thank you for your help

Try to declare the variable globally (outside of the function)
use the function to change the global variable.
Variables declared inside of a function are only accessible in that function; they are called local variables as they are local to the function in which they are declared.
The main() function cannot access the local variables of another function.
Globally declared variables are visible everywhere.

After the function is called, your array no longer exists:
void makeExampleStruct ()
{
exampleStruct exampleObj[30];
// exampleObj is created here
for (int r=0;r<=30;r++)
{
exampleObj[r].ID=r;
}
// exampleObj is destroyed here.
}
So even if you could access the object, it would be illegal to do so after the function returns, since the object's lifetime has ended.

No. You need to declare it outside the function otherwise it is local.

You cannot provide global access to local variables from functions. What you can do instead is something like making them static and return a reference:
exampleStruct[30]& makeExampleStruct () {
static exampleStruct exampleObj[30];
static bool isinitialized = false;
if(!isinitialized) {
for (int r=0;r<=30;r++) {
exampleObj[r].ID=r;
}
isinitialized = true;
}
return exampleObj;
}

Related

How to implement local variables that can be used in other places with the same conditions in C++

How to get the following code to work?
int main(){
bool flag = true;
if(flag){
// note that I donot want to define variable globally.
int a = 5;
}
if(flag){
// but I still want to use this local variable within the same condition.
a++;
}
}
Note that I don't want to define this variable globally or use a static variable.
I'm curious if there is a way for c++ to make local variables available in all regions with the same conditions?
What you ask for literally is a local variable that is not a local variable. Thats not possible.
On the other hand, you basically want data + code, thats a class. If you wrap it in a class your function can look like this:
int main(){
Foo f;
f.doSomething();
}
And the class can be this
struct Foo {
bool flag = false;
int a = 0;
void doSomething() {
if (flag) ++a;
}
};
What you're directly asking for isn't possible. You'll have to declare something up front. If it's about avoiding construction of objects until you have some relevant detail, you could use std::optional
int main()
{
std::optional<int> a;
if(flag)
{
a = 10;
}
if(a)
{
*a++;
}
}
You set the variable's scope to be the scope you want it to be.
int main(){
bool flag = true;
// declare it in this scope if you want it to persist
// thru this scope
int a;
if(flag){
a = 5;
}
if(flag){
a++;
}
}
No.
According to section 6.4.3, basic.scope.block:
1 Each
(1.1) selection or iteration statement ([stmt.select], [stmt.iter]),
[...]
(1.4) compound statement ([stmt.block]) that is not the compound-statement of a handler
introduces a block scope that includes that statement or handler.
A variable that belongs to a block scope is a block variable.
According to section 6.7.5.4, basic.stc.auto, clause 1:
Variables that belong to a block or parameter scope and are not explicitly declared static, thread_­local, or extern have automatic storage duration. The storage for these entities lasts until the block in which they are created exits.

How to make functions variables public, they are not in a class C++ [duplicate]

This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 8 months ago.
I would like to know how I can make a function's variable public to other functions.
Example:
void InHere
{
int one = 1; // I want to be public
}
int main()
{
InHere(); // This will set int one = 1
one = 2; // If the variable is public, I should be able to do this
return 0;
}
Does anyone know how to do this? The only things I find when searching is for classes, as you can see nothing is in a class and I don't want them to be in one.
Any help is really appreciated!
A variable defined locally to a function is generally inaccessible outside that function unless the function explicitly supplies a reference/pointer to that variable.
One option is for the function to explicitly return a reference or pointer to that variable to the caller. That gives undefined behaviour if the variable is not static, as it does not exist after the function returns.
int &InHere()
{
static int one = 1;
return one;
}
void some_other_func()
{
InHere() = 2;
}
This causes undefined behaviour if the variable one is not static since, as far as the program as a whole is concerned, the variable only comes into existence whes InHere() is called and ceases to exist as it returns (so the caller receives a dangling reference - a reference to something that no longer exists).
Another option is for the function to pass a pointer or reference to the variable as an argument to another function.
void do_something(int &variable)
{
variable = 2;
}
int InHere()
{
int one = 1;
do_something(one);
std::cout << one << '\n'; // will print 2
}
The downside is that this only provides access to functions CALLED BY InHere(). Although the variable does not need to be static in this case, the variable still ceases to exist as InHere() returns (so if you want to combine option 1 and option 2 in some way, the variable needs to be static)
A third option is to define the variable at file scope, so it has static storage duration (i.e. its lifetime is not related to the function);
int one;
void InHere()
{
one = 1;
}
void another_function()
{
one = 2;
}
int main()
{
InHere();
// one has value 1
some_other_function();
// one has value 2
}
A global variable can be accessed in any function that has visibility of a declaration of the variable. For example, we could do
extern int one; // declaration but not definition of one
int one; // definition of one. This can only appear ONCE into the entire program
void InHere()
{
one = 1;
}
And, in other source file
extern int one; // this provides visibility to one but relies on it
// being defined in another source file
void another_function()
{
one = 2;
}
int main()
{
InHere();
// one has value 1
some_other_function();
// one has value 2
}
Be careful with that though - there are numerous down-sides of global/static variables, to the extent they are usually considered VERY BAD programming technique. Have a look at this link (and pages linked to from there) for a description of some of the problems.
Just set the variable as a global variable. Then you can access it from other functions.
int one;
void InHere()
{
one = 1; // I want to be public
}
int main()
{
InHere(); // This will set int one = 1
one = 2; // If the variable is public, I should be able to do this
return 0;
}
if you want it inside a class, then try the code below
#include <iostream>
using namespace std;
class My_class
{
// private members
public: // public section
// public members, methods or attributes
int one;
void InHere();
};
void My_class::InHere()
{
one = 1; // it is public now
}
int main()
{
My_class obj;
obj.InHere(); // This will set one = 1
cout<<obj.one;
obj.one = 2; // If the variable is public, I should be able to do this
cout<<obj.one;
return 0;
}

using a member variable before its declaration? [duplicate]

This question already has answers here:
Do class functions/variables have to be declared before being used?
(5 answers)
Closed 6 years ago.
is it possible to use a member variable of a class before declaring it?
here is my code.
using namespace std;
class Computer
{
public:
Computer()
{
processor_speed = 0;
}
~Computer();
void setspeed (int);
int getspeed (void);
private:
int processor_speed;
};
/*Computer::Computer()
{
processor_speed = 0;
} */
Computer::~Computer()
{
cout<<"this is a destructor"<<endl;
}
void Computer:: setspeed(int p)
{
processor_speed = p;
}
int Computer::getspeed(void)
{
return processor_speed;
}
int main(void)
{
Computer obj;
cout<<"processor speed is "<<obj.getspeed()<<endl;
obj.setspeed(100);
cout<<"processor speed is now "<<obj.getspeed()<<endl;
return 0;
}
as u can see here i was able to use variable processor_speed before declaring it.
i saw a similar question here: Do class functions/variables have to be declared before being used?
but i was not able to understand the reason why this code work.
Thanks
Yes, you can do it.
A member variable is in scope for member functions of your class even if it is textually after its first point of use. The compiler translates your code in several "passes". One could think of it as getting all member variables first, and only then translating member functions, with all declarations in place.
Note that this is not allowed for "free-standing" global and static variables inside translation units: a declaration must precede the first use, otherwise you get an error.

Do functions have access to variables in the immediate outer scope without parameter input to the function in C++?

Do functions have access to variables in the immediate outerscope without parameter input to the function in C++?
=========
Here is a code I am working on
#include...
void ReadGrid();
void SaveGrid();
int main(){
ReadGrid();
}
void ReadGrid() {
int m=1;
int n[]={1,2,3};
vector<int> o(3,10);
SaveGrid();
}
void SaveGrid() {
int a=m;
int b=n[1];
int c=o[1];
}
Why can't I access the variables in the ReadGrid() functions in SaveGrid(), doesn't the local scope of SaveGrid() treat the scope of ReadGrid() as Global when SaveGrid() is called?
Your question might be better formed thus:
When function a() calls function b(), does b() automatically get visibility into all of a()'s local variables?
And the answer is … no. They are still different block scopes, regardless of your call stack.
Each set of braces denotes a separate scope, so if you create a block with braces, and declare variables inside them, they will not be viisble outside of it. If you create nested blocks of braces, they have inner block has access to the outer block, but not the other way around.
This also applies not only to function (which always have their scope), but also to blocks inside a function as well.
i.e. Two different variables named i, no nameclash because of different scopes:
{
int i;
}
{
int i;
}
Here we have access.
{
int i;
{
int x = i; <== in scope
}
int y = x; <== error
}
If you want to have a set ov variables assoicated to some logical function, then you should put them inside a class or struct.
No, but this is where objects can come into play, e.g. in this pseudo code they share the same data:
class Grid {
private:
int m;
int n[];
vector<int> o;
public:
void ReadGrid(){
// get m,n, and o
}
void SaveGrid() {
// put m,n, and o
}
}
int main(){
Grid grid;
grid.ReadGrid();
}
No what are trying to do is illogical.
If you want the value of m to be available to both ReadGrid and SaveGrid then you must defint "m" as a global variable and you can initialise it in ReadGrid and use the same value in SaveGrid.
Here is a snippet, for your reference
#include...
void ReadGrid();
void SaveGrid();
int m;// global variable
int n[];//global variable
int main(){
ReadGrid();
}
void ReadGrid() {
m=1;
n[]={1,2,3};
SaveGrid();
}
void SaveGrid() {
int a=m;
int b=n[1];
}

Static member function pointer to hold non static member function

This has defeated me. I want to have a static class variable which is a pointer to a (non-static) member function. I've tried all sorts of ways, but with no luck (including using typedefs, which just seemed to give me a different set of errors). In the code below I have the static class function pointer funcptr, and I can call it successfully from outside the class, but not from within the member function CallFuncptr - which is what I want to do. Any suggestions?
#include <stdio.h>
class A
{
public:
static int (A::*funcptr)();
int Four() { return 4;};
int CallFuncptr() { return (this->*funcptr)(); }
// doesn't link - undefined reference to `A::funcptr'
};
int (A::*funcptr)() = &A::Four;
int main()
{
A fred;
printf("four? %d\n", (fred.*funcptr)()); // This works
printf("four? %d\n", fred.CallFuncptr()); // But this is the way I want to call it
}
Try this instead:
#include <iostream>
class A {
public:
typedef int (A::*AMemFn)();
static AMemFn funcptr;
int Four() { return 4; }
int CallFuncptr() { return (this->*funcptr)(); }
};
A::AMemFn A::funcptr = &A::Four;
int main()
{
A fred;
std::cout << "four? " << fred.CallFuncptr() << std::endl;
}
jweyrich has a nice looking work around (and I suggest you use it), but I thought I'd elaborate on what the real problem in the code is:
Your problem is this line:
int (A::*funcptr)() = &A::Four;
This is defining a global variable called funcptr that is of the right type, rather than A::funcptr.
What you need is this mess:
int (A::*(A::funcptr))() = &A::Four;
This ugly mess is why I suggest you go down the typedef path to get a nice looking version like jweyrich's solution.
A static variable is not a member of a particular object -- it can only be accessed through the classes namespace. CallFuncptr should be rewritten:
int CallFuncptr() { return (*funcptr)();
which I think should work, since this function can access functions in A's namespace without specifying it.
Also, function pointers are more of a C construct than C++. You can access the static variable outside the class with the code:
A::CallFuncptr
since CallFunctptr just resides in A's namespace