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.
Related
#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;
}
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.
In a program I'm working on, I've declared a vector in main. I have two functions that use the vector: an int function, and a standard void 'print' function. I'm attempting to use a function pointer (pointing to the int function) in the void function, but I get the error that the vector has not been declared, even though it's in main. I've tried declaring the vector outside of main, and the function worked fine, but I'm hesitant on keeping it outside of main. I was wondering if there was some way to use the vector in the void function when it was declared in main. Here's some example code for what I'm asking:
// Example program
#include <iostream>
#include <vector>
using namespace std;
int returnSquare(vector<int>& numbers);
void print(int (*squarePtr)(vector<int>&));
int (*squarePtr)(vector<int>&);
int main()
{
vector<int> v(1);
squarePtr = &returnSquare;
for(int i = 0; i < v.size(); i++)
{
v.at(i) = i * 25;
cout << v.at(i) << " ";
}
print(squarePtr);
return 0;
}
int returnSquare(vector<int>& numbers)
{
int product = 0;
for(int i = 0; i < numbers.size(); i++)
{
product = numbers.at(i) * numbers.at(i);
}
return product;
}
void print(int (*squarePtr)(vector<int>&))
{
int answer = (*squarePtr)(v);
cout << answer << endl;
}
In your function print you have just one parameter. To call your squaring function you need to pass the vector to square to it, something like:
void print(int (*squarePtr)(vector<int>&), vector<int> &v)
{
int answer = (*squarePtr)(v);
cout << answer << endl;
}
Without that the variable v is not visible inside the function. The call should look like:
print(squarePtr, v);
Less important. You use the squarePtr name in your global definitions twice. This does not bring clarity to your code. You better write:
void print(int (*workerFuncPtr)(vector<int>&));
int (*squarePtr)(vector<int>&);
void print (int (*squarePtr)(vector<int>&))
This parameter only accepts a pointer to your square function, that's it. It doesn't hold a pointer or a reference to your v variable. Your print function has no idea what v is, unless you pass v as an argument, or make v a global variable (which is what you did moving it out of main).
Do this:
// Modify your print definition to accept a reference to your vector `v`
void print(int (*squarePtr)(vector<int>&), vector<int>& v);
// Add `v` as the second argument to your print call
print(squarePtr, v);
// Modify the definition of your print function to accept a reference to your vector `v`
void print(int (*squarePtr)(vector<int>&), vector<int>& v)
{
...
}
I made a program that calls this function. I know this because "Int Strength has been called" appears in the output box. However, it will not change the values that I tell it to do.
I want it to get integer values from main(), then use them and return the new values.
I am using a header file that only contains "int strength(int a, int s, int i)"
int strength(int a, int s, int i)
{
using namespace std;
cout << "Int Strength has been called" << endl;
a = a + i;
s = s - i;
return a;
return s;
}
Multiple errors. Firstly, if you want the arguments to be modified (more precisely, the modification being effective out of the scope of the function), you have to pass the values by reference:
int strength(int &a, int &s, int &i)
Second, you seem to be concerned about return a; return s; returning two values. It doesn't - the very first return encountered exits the function immediately.
The values only change within the function. Variables are passed by value not reference.
Use references as the parameters.
int strength(int& a, int& s, int& i)
You're passing by value. You need to pass a pointer to the memory allocated in the caller that contains the data you wish to modify.
void strength(int *a, int *s, int i)
{
using namespace std;
cout << "Int Strength has been called" << endl;
*a += i;
*s -= i;
}
Then call it thusly:
a = 1;
s = 2;
i = 3;
strength(&a, &s, i);
I'm starting with developing, sorry about this newbie question.
I need to create a function that swap values between 2 vars.
I have wrote this code, but no changes are made in vars, What should I change? What is my mistake?
#include <iostream>
using namespace std;
void swap_values( int x, int y);
int main(void) {
int a,b;
a = 2;
b = 5;
cout << "Before: " << a << " " << b << endl;
swap_values( a,b );
cout << "After: " << a << " " << b << endl;
}
void swap_values( int x, int y ){
int z;
z = y;
y = x;
x = z;
}
You need to pass the variables by reference:
void swap_values( int& x, int& y )
{
int z;
z = y;
y = x;
x = z;
}
pass-by-value and pass-by-reference are key concepts in major programming languages. In C++, unless you specify by-reference, a pass-by-value occurs.
It basically means that it's not the original variables that are passed to the function, but copies.
That's why, outside the function, the variables remained the same - because inside the functions, only the copies were modified.
If you pass by reference (int& x, int& y), the function operates on the original variables.
You need to understand that by default, C++ use a call-by-value calling convention.
When you call swap_values, its stack frame receives a copy of the values passed to it as parameters. Thus, the parameters int x, int y are completely independent of the caller, and the variables int a, b.
Fortunately for you, C++ also support call-by-reference (see wikipedia, or a good programming language design textbook on that), which essentially means that the variables in your function are bound to (or, an alias of) the variables in the caller (this is a gross simplification).
The syntax for call-by-reference is:
void swap_values( int &x, int &y ){
// do your swap here
}
you are passing by value. you can still pass by value but need to work with pointers.
here is the correct code needed:
void swap(int *i, int *j) {
int t = *i;
*i = *j;
*j = t;
}
void main() {
int a = 23, b = 47;
printf("Before. a: %d, b: %d\n", a, b);
swap(&a, &b);
printf("After . a: %d, b: %d\n", a, b);
}
also a small document that explains "by reference" vs "by value" : http://www.tech-recipes.com/rx/1232/c-pointers-pass-by-value-pass-by-reference/