I have a program that uses 3 separate files, a header file for function declarations, a cpp file for the definitions, and a main driver file to call the functions. For my function definitions, I have variables being created inside these functions that I wish to use as parameters for another function being called in main. I'm confusing myself just trying to put it into words, below is an example.
Header File
void function01(char);
void function02(int, int, char);
Cpp File
void function01(char a){
int var01 = 3;
int var02 = 4;
int var03 = 8;
char a = 'a';
}
void function02(int num1, int num2, int num3){
int sum = num1 + num2 + num3;
}
Main File
int main (void){
function02(var01, var02, var03);
return 0;
}
I know that as it is written now an error would be called. But is there anyway I can access the variables used in this first function so that I can call those same variables in main and pass them into my second function?
How to access the variables of a function inside main?
It is not possible to access non-static local variables of a function in a scope where that function is being called. Those variables exist only during function's execution. The objects named by the variables are created when the function is called, and destroyed before the function returns.
function01 is currently completely useless because it neither has any effects observable to the outside of the function, nor does it return anything. After calling the function the state of the program would be exactly the same as if you hadn't called the function. The function also doesn't do anything with its argument.
What you can do instead is return values from a function. It is only possible to return a single value. But you can group multiple objects inside a class. You could rewrite function01 like this for example:
struct my_example_class {
int var01;
int var02;
int var03;
char a;
};
my_example_class
function01(){
return {3, 4, 8, 'a'};
}
Then call the other function and use the returned member objects as arguments to the other function:
auto r = function01();
function02(r.var01, r.var02, r.var03);
Related
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;
}
we are able to declare the main keyword as a variable name(without an error); however, the same is not true for other functions(i.e. user defined functions). Why is this?
Thank you.
(a code using a user defined function and the same variable name produces an error: error: 'int stardooms' redeclared as different kind of symbol
note: previous declaration 'int stardooms(int)'
#include<iostream>
int main(){
int stardooms(int);
int stardooms;
std::cout<<stardooms(5);
return 0;
}
int stardooms(int a){
if(a)
return a;
return 0;
}
the same is not true in this instance (the code produces result 5 without any error)
#include<iostream>
int main(){
int main=5;
std::cout<<main;
return 0;
}
A name which is declared in a scope will hide a declaration of the same name in an outer scope. A name must not have multiple conflicting declarations in a given scope, or you'll get the error you saw.
In your second example, there's only one declaration of main in the function scope, which hides the declaration int main() from the outer slope. (Function names are in the outer scope, not from their own scopes.) In your first example, there's two declarations of stardooms in the function scope.
If you were to also redeclare int main() in the function scope in your second example, you'd see the same error. Likewise, if you were to move the definition of the function stardooms before the definition of the function main, and remove the declaration int stardooms(int) from the scope of the main function, you wouldn't get that error (but you'd get a different one from attempting to use an integer like a function).
Unlike Pascal, C++ doesn't allow a function to be defined inside another function. All the functions are taken as independent and equal, which means that you should move the function prototype of stardooms() outside the function body of main(). The correct code is follwing:
#include<iostream>
int stardooms(int);
int main(){
std::cout<< stardooms(5);
return 0;
}
int stardooms(int a){
if(a)
return a;
return 0;
}
I'm trying to use a static variable as a counter for the number of times a function has been called. Essentially, I'm having function A call function B a number of times, and I want function B to return that value to function A so it can be displayed. An example of my test code is below(here main is function A and showStat is function B). As of now the output is 012340; the desired output is 012344. Thanks in advance.
int showStat()
{
static int statNum;
cout<<statNum; //function check
statNum++;
return statNum;
}
int main()
{
int statNum;
for( int i = 0; i < 5 ; i++)
{
showStat();
}
cout<<statNum;
return 0;
}
In main, change
showStat();
to
statNum = showStat();
You have two variables called statNum. Apparently the counting takes place in the static variable inside showStat() function. But in main() without reading the return value of showStat(), you are just printing the uninitialized local variable, which the compiler happened to assign an initial value 0.
I'm relatively new to c++ and used to Java (which I like better).
I've got some pointer problem here. I created a minimal programm to simulate the behaviour of a more complex programm.
This is the code:
void test (int);
void test2(int*);
int* global [5]; //Array of int-pointer
int main(int argc, char** argv) {
int z = 3;
int y = 5;
cin >> z; // get some number
global[0] = &y; // global 0 points on y
test(z); // the corpus delicti
//just printing stuff
cout << global[0]<<endl; //target address in pointer
cout << &global[0]<<endl; //address of pointer
cout << *global[0]<<endl; //target of pointer
return 0; //whatever
}
//function doing random stuff and calling test2
void test (int b){
int i = b*b;
test2(&i);
return;
}
//test2 called by test puts the address of int i (defined in test) into global[0]
void test2(int* j){
global[0]= j;
}
The tricky part is test2. I put the address of a variable I created in test into the global pointer array. Unfortunately, this program gives me a compiler error:
main.cpp: In function 'int test(int)':
main.cpp:42:20: error: 'test2' was not declared in this scope
return test2(&i);
^
I can't find any scope problem here. I tried changing the int i of test into a global variable, but it didnt help, so I suppose, this isnt the reason.
Edit: It compiles now, but gives for cin = 20 the wrong values. *global[0] should be 400, but is 2130567168. It doesnt seem to be a int/uint problem. It is too far from 2,14e9.
Edit2: The input value doesnt matter.
'test2' was not declared in this scope It's because the compiler doesn't know what test2 is. You need to add a function prototype above the main.
void test (int b);
void test2(int& j);
or just:
void test (int);
void test2(int&);
because at this time compiler only need to know the type of the arguments and not their names.
EDIT: Moving the function definition above the main without adding the prototype will also work, but it's better to use the prototypes.
Before a function can be called, the compiler must know about it.
So you either rearrange your function definitions such that test2 comes first, test second and main last, or you put declarations of test2 and test1 before main:
void test2(int& j); // declaration
void test(int b); // declaration
int main(int argc, char** argv) {
// ...
}
void test(int b){ // definition
// ...
}
void test2(int& j) { // definition
// ...
}
This will then reveal a more serious error; you are calling test2 with an int*, but it expects an int&. You can fix this by turning the call into test2(i);.
Once your functions are neatly split into declarations and definitions, it's time to perform the next step towards the typical C++ source-file management: put the declarations into header files (usually *.h or *.hpp) and #include them from the implementation file (usually *.cpp) that contains main. Then add two more implementation files for the two function definitions. Add corresponding #includes there, too. Don't forget about include guards in the headers.
Finally, compile the three implementation files separately and use a linker to create an executable from the three resulting object files.
you need to declare test2 before you call it. Every function needs to be declared before it is called.
add these lines above main to declare the functions;
void test2(int& j);
void test2(int& j);
int main(){...}
I’ve a bit confusion about static, auto, global and local variables.
Somewhere I read that a static variable can only be accessed within the function, but they still exist (remain in the memory) after the function returns.
However, I also know that a local variable also does the same, so what is the difference?
There are two separate concepts here:
scope, which determines where a name can be accessed, and
storage duration, which determines when a variable is created and destroyed.
Local variables (pedantically, variables with block scope) are only accessible within the block of code in which they are declared:
void f() {
int i;
i = 1; // OK: in scope
}
void g() {
i = 2; // Error: not in scope
}
Global variables (pedantically, variables with file scope (in C) or namespace scope (in C++)) are accessible at any point after their declaration:
int i;
void f() {
i = 1; // OK: in scope
}
void g() {
i = 2; // OK: still in scope
}
(In C++, the situation is more complicated since namespaces can be closed and reopened, and scopes other than the current one can be accessed, and names can also have class scope. But that's getting very off-topic.)
Automatic variables (pedantically, variables with automatic storage duration) are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered.
for (int i = 0; i < 5; ++i) {
int n = 0;
printf("%d ", ++n); // prints 1 1 1 1 1 - the previous value is lost
}
Static variables (pedantically, variables with static storage duration) have a lifetime that lasts until the end of the program. If they are local variables, then their value persists when execution leaves their scope.
for (int i = 0; i < 5; ++i) {
static int n = 0;
printf("%d ", ++n); // prints 1 2 3 4 5 - the value persists
}
Note that the static keyword has various meanings apart from static storage duration. On a global variable or function, it gives it internal linkage so that it's not accessible from other translation units; on a C++ class member, it means there's one instance per class rather than one per object. Also, in C++ the auto keyword no longer means automatic storage duration; it now means automatic type, deduced from the variable's initialiser.
First of all i say that you should google this as it is defined in detail in many places
Local
These variables only exist inside the specific function that creates them. They are unknown to other functions and to the main program. As such, they are normally implemented using a stack. Local variables cease to exist once the function that created them is completed. They are recreated each time a function is executed or called.
Global
These variables can be accessed (ie known) by any function comprising the program. They are implemented by associating memory locations with variable names. They do not get recreated if the function is recalled.
/* Demonstrating Global variables */
#include <stdio.h>
int add_numbers( void ); /* ANSI function prototype */
/* These are global variables and can be accessed by functions from this point on */
int value1, value2, value3;
int add_numbers( void )
{
auto int result;
result = value1 + value2 + value3;
return result;
}
main()
{
auto int result;
value1 = 10;
value2 = 20;
value3 = 30;
result = add_numbers();
printf("The sum of %d + %d + %d is %d\n",
value1, value2, value3, final_result);
}
Sample Program Output
The sum of 10 + 20 + 30 is 60
The scope of global variables can be restricted by carefully placing the declaration. They are visible from the declaration until the end of the current source file.
#include <stdio.h>
void no_access( void ); /* ANSI function prototype */
void all_access( void );
static int n2; /* n2 is known from this point onwards */
void no_access( void )
{
n1 = 10; /* illegal, n1 not yet known */
n2 = 5; /* valid */
}
static int n1; /* n1 is known from this point onwards */
void all_access( void )
{
n1 = 10; /* valid */
n2 = 3; /* valid */
}
Static: Static object is an object that persists from the time it's constructed until the end of the program. So, stack and heap objects are excluded. But global objects, objects at namespace scope, objects declared static inside classes/functions, and objects declared at file scope are included in static objects. Static objects are destroyed when the program stops running.I suggest you to see this tutorial list
AUTO:C, C++
(Called automatic variables.)
All variables declared within a block of code are automatic by default, but this can be made explicit with the auto keyword.[note 1] An uninitialized automatic variable has an undefined value until it is assigned a valid value of its type.[1]
Using the storage class register instead of auto is a hint to the compiler to cache the variable in a processor register. Other than not allowing the referencing operator (&) to be used on the variable or any of its subcomponents, the compiler is free to ignore the hint.
In C++, the constructor of automatic variables is called when the execution reaches the place of declaration. The destructor is called when it reaches the end of the given program block (program blocks are surrounded by curly brackets). This feature is often used to manage resource allocation and deallocation, like opening and then automatically closing files or freeing up memory.SEE WIKIPEDIA
Difference is static variables are those variables: which allows a value to be retained from one call of the function to another.
But in case of local variables the scope is till the block/ function lifetime.
For Example:
#include <stdio.h>
void func() {
static int x = 0; // x is initialized only once across three calls of func()
printf("%d\n", x); // outputs the value of x
x = x + 1;
}
int main(int argc, char * const argv[]) {
func(); // prints 0
func(); // prints 1
func(); // prints 2
return 0;
}
Local variables are non existent in the memory after the function termination.
However static variables remain allocated in the memory throughout the life of the program irrespective of whatever function.
Additionally from your question, static variables can be declared locally in class or function scope and globally in namespace or file scope. They are allocated the memory from beginning to end, it's just the initialization which happens sooner or later.
static is a heavily overloaded word in C and C++. static variables in the context of a function are variables that hold their values between calls. They exist for the duration of the program.
local variables persist only for the lifetime of a function or whatever their enclosing scope is. For example:
void foo()
{
int i, j, k;
//initialize, do stuff
} //i, j, k fall out of scope, no longer exist
Sometimes this scoping is used on purpose with { } blocks:
{
int i, j, k;
//...
} //i, j, k now out of scope
global variables exist for the duration of the program.
auto is now different in C and C++. auto in C was a (superfluous) way of specifying a local variable. In C++11, auto is now used to automatically derive the type of a value/expression.
When a variable is declared static inside a class then it becomes a shared variable for all objects of that class which means that the variable is longer specific to any object.
For example: -
#include<iostream.h>
#include<conio.h>
class test
{
void fun()
{
static int a=0;
a++;
cout<<"Value of a = "<<a<<"\n";
}
};
void main()
{
clrscr();
test obj1;
test obj2;
test obj3;
obj1.fun();
obj2.fun();
obj3.fun();
getch();
}
This program will generate the following output: -
Value of a = 1
Value of a = 2
Value of a = 3
The same goes for globally declared static variable. The above code will generate the same output if we declare the variable a outside function void fun()
Whereas if u remove the keyword static and declare a as a non-static local/global variable then the output will be as follows: -
Value of a = 1
Value of a = 1
Value of a = 1