#include <iostream>
using namespace std;
void b();
int main() {
int a = 10;
b();
}
void b() {
int a;
cout<<"Int a="<<a;
}
I am looking to print the value of a in the main scope using a function, with my current code, it prints Int a=0. How can I achieve this?
Don't declare an entirely new a inside b().
Pass the a from main to b() and then print that.
For example:
#include <iostream>
void b(int whatever_name_you_want_here);
int main()
{
int a = 10;
b(a);
}
void b(int whatever_name_you_want_here)
{
std::cout << "Int a=" << whatever_name_you_want_here;
}
//Change your code to the following and it will give you the result you're looking for.
On your code there is no way to pass int a on the main to b(); unless b accepts a parameter of the type you want the function to output.
#include<iostream>
void b(int);
int main()
{
int a = 10;
b(a);
}
void b(int a){
std::cout << "int a=" << a;
}
I guess the main problem is not being aware of something very important which is called scope! Scopes are usually opened by { and closed by }
unless you create a global variable, it is only known inside the scope it has been introduced (declared).
you declared the function b in global scope :
void b();
so after this every other function including main is aware of it and can use it.
but you declared the variable a inside the scope of main:
int a = 5;
so only main knows it and can use it.
Please make note that unlike some other programming languages, names are not unique and not every part of the program recognize them in c and c++.
So the part:
void b() {
int a;
does not force the function b to recognize the a which was declared in main function and it is a new a.
so to correct this mistake simply give the value or reference of variable a to function b :
#include <iostream>
void b(int&);
int main() {
int a = 10;
b(a);
}
void b(int& a) {
std::cout << "Int a=" << a << std::endl;
}
please also note that the a as argument of the function b is not the same a in the function main.
The final tip is every argument for functions is known inside that function scope as it was declared inside the function scope!
What you want to achieve requires you to pass a value to a function. Let me give you an example on how to do that.
#include<iostream>
void print_value(int value){
std::cout << "Value is: " << value << '\n';
}
int main(){
int a = 5;
print_value(a);
return 0;
}
The only thing you are missing in your program is the parameter. I won't bother explaining the whole thing over here as there are numerous articles online. Here is a straightforward one.
Refer to this to understand how functions work in C++
Use pass by reference to access a variable which is declared in one function in another.
Refer the below code to understand the use of reference variable,
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}
#include <iostream>
using namespace std;
void displayValue(int number) {
cout<<"Number is = "<<number;
}
int main()
{
int myValue = 77;
displayValue(myValue);
return 0;
}
Related
C++ Program: - I know that in the function definition, x is not passed so it would get error message but i want to increase in function, so what can i do?
#include <iostream>
using namespace std;
fun(int& p)
{
cout << p;
x++;
}
int main()
{
int x = 15;
int c = 1;
fun(c);
cout << x;
return 0;
}
The value of variable x is undefined for fun() and you should go through a book for basics.
The only method if you just want to manipulate the same variables, is using reference variables as parameters and then you can directly modify its original values.
Refined version of your program for accessing and manipulating the data with functions:
#include <iostream>
void fun(int &, int &);
int main(void) {
int x = 15;
int c = 1;
fun(c, x); // c is printed "1" and x increments with 1
std::cout << x << std::endl; // new value of x prints
return 0;
}
void fun(int & p, int & x) {
std::cout << p << std::endl;
x++; // increments original x
}
Note: Alternatively, you can declare your required variable in global scope by putting them outside of all the functions and underneath the header declaration, so that they'll be visible to the entire program but remember that you must need to use reference for changing the variable values for the whole program.
You can either set x as a global variable or you can also pass it to your function.
fun(int &p, int &x) and then call it from main.
I apologize for posting such a basic question, but I cant find a decent answer as to why this doesn't work, and how to get it to work.
I have simplified my issue here:
#include <iostream>
using namespace std;
class A {
public:
int x;
};
void otherFunction() {
A A;
cout<<"X: "<<A.x<<endl;
}
int main(){
A A;
A.x = 5;
otherFunction();
return 0;
}
Do the class members become constant after constructing?
How do I expand the scope of changes done to the class?
Are structs limited in this way?
Thank you in advance for answers.
You are not getting the expected output because in otherFunction() you are creating a new object of type A for which you have not assigned a value before!
Read up on scope of a variable in C++ to learn more
Try running the code given below, you should get the output as 5.
#include <iostream>
using namespace std;
class A {
public:
int x;
};
void otherFunction(A a) {
cout << "X: " << a.x << endl;
}
int main(){
A a;
a.x = 5;
otherFunction(a);
return 0;
}
Alternatively you can do this, which is considered a good practice in OOP
class A{
private:
int x;
public:
void update(int newx){
x = newx;
}
int getX(){
return x;
}
};
int main(){
A a;
a.update(5);
cout << a.getX() << endl;
return 0;
}
It is doing what it is supposed to do.
You are creating a new object A inside the function otherFunction, this new object will be local to the function.
Print the the value of A.x after the call of function otherFunction in the main , you will see the the value of A.x has changed.
The variable A in main is not the same as the variable A in otherFunction, so they won't have the same value.
One way to give otherFunction access to the value of A in main is to pass it in as a parameter. For example:
void otherFunction(A p) {
cout<<"X: "<<p.x<<endl;
}
int main(){
A a;
a.x = 5;
otherFunction(a);
return 0;
}
I have changed the names of the variables to make it a bit more clear. a is in main, and a copy of a is passed into otherFunction. That copy is called p in otherFunction. Chnages that otherFunction makes to p will not cause any change to a.If you want to do that, you would need to pass by reference, which is probably a topic a bit further along than you are now.
I want to create a class which has a static method that returns a reference to a static variable(which is declared inside the method). What I want is when calling the method to get the reference of the static variable. Then when I modify it outside the class and call the method again to get the same value I previously set.
Here's what I tried:
#include <iostream>
using namespace std;
class A
{
public:
static int& f()
{
static int i;
return i;
}
};
int main()
{
static int i;
i = A::f();
cout << i << endl;
i = 11;
cout << i << endl;
i = A::f();
cout << i << endl;
return 0;
}
The problem is that the output of this code is:
0
11
0
Press <RETURN> to close this window...
Why doesn't it return 0, 11, 11 and how can I make it return 0, 11, 11?
Note: I want the static variable to be explicitly declared inside the method and not as member.
Thanks!
This is because you copy the value returned by reference into a regular variable: when you store int& in an int, it is no longer a reference.
What you should do instead is
int &i = A::f();
Note that the local i needs not be static: reference to static data can be stored in automatic variables without a problem.
To have the local variable i refer to the same variable inside the function, declare it as a reference:
static int& i = A::f();
Otherwise, you're just creating a new variable and using assigning A::f() to it.
It needs to be an int& in main, if you want changes to that int to be changes to the int referred to by the return value of f.
You may want to initailce your variable. And you can use it directly or you may want to "conserv" the reference in a local reference.
But you can not reasign these local references. For example:
int main()
{
A::f()=3;
cout << A::f() << endl;
static int &i = A::f();
cout << i << endl;
i = 11;
cout << i << endl;
cout << A::f() << endl;
int &ii = A::f();
cout << ii << endl;
return 0;
}
I tried asking before but I wasn't very clear so I'm re-asking it.
I want to have a variable that depends on the value of another variable, like b in this example:
int main(){
int a;
dependent int b=a+1; //I'm just making this up
a=3;
cout << b; //prints 4
a=4;
cout << b; //prints 5
}
Of course, this does not exist in C++, but this is what I want.
So instead I tried making a function:
int main(){
int a;
int b(){ return a+1; } //error
a=3;
cout << b(); //would print 4 if C++ allowed nested functions
a=4;
cout << b(); //would print 5 if C++ allowed nested functions
}
The above doesn't work because C++ doesn't allow nested functions.
I can only make functions outside of main(), like this:
int b(){
return a+1; //doesn't work because a is not in scope
}
int main(){
int a;
a=3;
cout << b();
a=4;
cout << b();
}
But this does not work because a is not in the same scope as b(), so I would have to pass a as a parameter and I don't want to do that.
Are there any tricks to get something similar to a dependent variable working in C++?
What you need is a closure. If you can use C++ 0x features, you are in luck. Otherwise, you can define one manually:
#include <iostream>
using namespace std;
struct B
{
const int & a;
B(const int & a) : a(a) {}
// variable syntax (Sean Farell's idea)
operator int () const { return a + 1; }
// function syntax
int operator () () const { return a + 1; }
};
int main()
{
int a;
B b(a);
a = 3;
cout << b << '\n'; // variable syntax
a = 4;
cout << b() << '\n'; // function syntax
}
You can also define B inside main, but some compilers would not like it.
The C++ 0x lambda syntax looks like this:
auto b = [&]() { return a + 1; }
The [&] means that the lambda captures local variables by reference.
If you're using C++0x (GCC 4.5+, Visual C++ 2010), you can use lambdas:
int a = 5;
auto b = [&a]{ return a + 1; };
std::cout << b() << std::endl;
Depending on what you're doing, though, there are probably cleaner solutions - possibly some variation of the classic "method that takes in 'a' and returns 'b'"
You could define a class that had a member a, and then a function b() that returned the value of a+1. A basic implementation would be something like:
class Dependent {
public:
Dependent(void) { m_value = 0; }
void set(int value) { m_value = value; }
int b(void) { return(m_value + 1); }
private:
int m_value;
};
int main(){
Dependent a;
a.set(3);
cout << a.b();
a.set(4);
cout << a.b();
}
You could add operator overloading as appropriate to make it work more like normal integers if you so desired.
This is possible if you use lambda functions (c++0x), because they can capture local variables.
Example:
int main()
{
int a;
auto f = [&] () -> int { return a + 1; };
a = 3;
std::cout << f() << std::endl;
a = 4;
std::cout << f() << std::endl;
return 0;
}
Result:
4
5
(See http://ideone.com/MlzX7 for proof)
A simple approach is to use pre-processor macros, nothing C++ specific about it though:
#define b ((a)+1)
int main(){
int a;
a=3;
cout << b;
a=4;
cout << b;
}
#undef b
Are you OK using C++0x ? if yes,
int main()
{
int a = 10;
auto b = [&a]() -> int { return a + 1; };
cout << b() << endl;
}
Since, it is not tagged with c++0x, you can use nested classes instead of nested functions. This column from Herb sutter would help you for existing c++. http://www.gotw.ca/gotw/058.htm
The above doesn't work because C++ doesn't allow nested functions.
You can simulate that using nested structure. In C++0x you can make use of lambda function, which provides the same means of function inside function.
Define a class called LinkedInt or something that behaves like an int, but has a RelatedTo relationship on itself and an additional member that is a function pointer to the function to evaluate when computing the integer's value. Pretty straightforward. Let me know if you need some pointers on the coding.
The short answer is that OOP is more than enough to bury this problem.
I want to have a variable that depends on the value of another
variable, like b in this example:
I see you just need a reference variable:
int a;
int &b =a;
a=10;
cout << b; // 10
Why C++0x lambdas do come for this, I dont understand.
In C++, what is the scope resolution ("order of precedence") for shadowed variable names? I can't seem to find a concise answer online.
For example:
#include <iostream>
int shadowed = 1;
struct Foo
{
Foo() : shadowed(2) {}
void bar(int shadowed = 3)
{
std::cout << shadowed << std::endl;
// What does this output?
{
int shadowed = 4;
std::cout << shadowed << std::endl;
// What does this output?
}
}
int shadowed;
};
int main()
{
Foo().bar();
}
I can't think of any other scopes where a variable might conflict. Please let me know if I missed one.
What is the order of priority for all four shadow variables when inside the bar member function?
Your first example outputs 3. Your second outputs 4.
The general rule of thumb is that lookup proceeds from the "most local" to the "least local" variable. Therefore, precedence here is block -> local -> class -> global.
You can also access each most versions of the shadowed variable explicitly:
// See http://ideone.com/p8Ud5n
#include <iostream>
int shadowed = 1;
struct Foo
{
int shadowed;
Foo() : shadowed(2) {}
void bar(int shadowed = 3);
};
void Foo::bar(int shadowed)
{
std::cout << ::shadowed << std::endl; //Prints 1
std::cout << this->shadowed << std::endl; //Prints 2
std::cout << shadowed << std::endl; //Prints 3
{
int shadowed = 4;
std::cout << ::shadowed << std::endl; //Prints 1
std::cout << this->shadowed << std::endl; //Prints 2
//It is not possible to print the argument version of shadowed
//here.
std::cout << shadowed << std::endl; //Prints 4
}
}
int main()
{
Foo().bar();
}
It should print out 3. The basic rule is mostly to work your way backward through the file to the most recent definition the compiler would have seen (edit: that hasn't gone out of scope), and that's what it uses. For variables that are local to a class, you follow the same except that all class variables are treated as if they were defined at the beginning of the class definition. Note that this is more or less unique to classes though. For example, given code like:
int i;
int x() {
std::cout << i << '\n'; // prints 0;
int i=1;
}
Even though there is an i that's local to the function, the most recent definition seen where cout is used is the global, so that's what the i in that expression refers to. If, however, this were in a class:
int i;
class X {
void y() { std::cout << i << "\n"; }
X() : i(2) {}
int i;
};
Then the cout expression would refer to X::i even though its definition hasn't been seen yet when y is being parsed.