C++ how to change the value of a - c++

here is the question I have, i got this code and it needs to write out 2, 5, 1, for the variables a, b, c.
But the catch is the main should not change, only the function. I managed to change the b to 5, but I really don't know how to change a to 2 without using pointeres.
Here's the code:
#include <iostream>
using namespace std;
int& function(int a, int* b, int c) {
return *b;
}
int main()
{
int a, b, c;
a = b = c = 1;
function(a, &b, c) = 5;
cout << a << " , " << b << " , " << c << endl;
return 0;
}
Every help will be highly appreciated.
I tried using pointers but the main should not be changed.

If you can't modify the function signature, then it is a terrible question. As written, it is impossible. The compiler is allowed to assume a will stay 1.
There's a kind of professors I've seen that would want you to turn in:
int& function(int a, int* b, int c)
{
b[1] = 2;
return *b;
}
But this relies on UB, a specific architecture and disabling optimization. https://godbolt.org/z/rc1d9oqab
If you are allowed to modify the function signature, yeah, then pass a reference for a.

Related

Using variables in a function from another function

In function foo() there is a loop that iterates until it finds an optimum set of variables and determines that as the ideal set. The function only returns one variable, in order to pass a unit test.
In the next function bar(), I need to output all of the variables in function foo() as it iterates. First output the optimum set of variables, and then the rest of the possible variable sets seperately.
int foo(int a, int b) {
int c, d;
while ( etc. ) {
c = arithmetic_for_c;
d = arithmetic_for_d;
e = c + d;
}
return e;
}
int bar(a, b) {
cout << e;
cout << c << d;
}
This example is very simple, but you get the idea.
I have a feeling references (int&, string& etc) would help somehow, but I'm not sure how they would be used here.
I tried to put together a global array but that seemed to get a bit too complex for the scope of this assignment.
The loop is a necessity, but also seems to ruin any hope for variables or arrays in the global scope.
Unfortunately there are a number of things we haven't learned yet, so there is likely a solution I can't use yet.
Thoughts?
Thank you!
Unless you want to go really fancy (probably not within your reach, yet), foo() has to help bar() a little.
Since you want to show the end result first, then the intermediate data later, you will have to find some way of storing the intermediate states. You could do so, using arrays or lists and push the intermediate values into them.
But another, probably shorter option is, to just store the intermediate output.
You know how to use std::cout by now, which prints output to the console.
It is of type std::ostream. And next to output to a console (or file etc.), the c++ standard library also allows to output to a string.
So, for your use case to work, you create such a string stream, then call bar and give it as output stream the string stream.
At the end of your calculations, you call bar with the regular output stream to print the end result, then, you output the string of the string stream to the regular output stream.
It sounds more convoluted, than it actually is, if you see it in code:
#include <iostream>
#include <sstream>
void bar(int a, int b, int c, int d, int e, std::ostream& os) {
os
<< "a: " << a
<< " b: " << b
<< " c: " << c
<< " d: " << d
<< " e: " << e
<< std::endl;
}
int foo(int a, int b, std::ostream& os ) {
std::ostringstream ossteps;
int c= 0;
int d= 1;
int e= 42;
while (c < 10) {
bar(a,b,c,d,e,ossteps);
c++;
d += c*c;
e = (a * b) - d;
}
bar(a,b,c,d,e,os);
os << ossteps.str();
return e;
}
int main (int argc, const char* argv[]) {
int efinal = foo(1,2, std::cout);
return 0;
}
If I'm not mistaken, this is not really possible in C++, as the variables are declared in the scope of the function foo, and cannot be accessed from a different scope. But you can always use something like this:
Pass by reference (out parameters):
#include <iostream>
// Declaring bar earlier as it has to be accessed by foo
int bar(int& c, int& d) {
int e = 0; // Declaring and initializing variable e
int count = 0;
// Loop
while (count < 10) {
c++;
d += 2;
e = c + d;
count++;
}
return e; // Return variable e
}
int foo(int a, int b) {
int c, d;
c = a, d = b; // setting c = parameter a, d = parameter b
int e = a + b;
std::cout << c << d << std::endl; // Printing variables c and d
std::cout << e << std::endl; // Printing variable e
e = bar(c, d); // Calling bar function. Also this function increments c by 10 and d by 20.
std::cout << c << d << std::endl; // Printing variables c and d
std::cout << e << std::endl; // Printing variable e
return e; // Return variable e
}
int main() {
foo(10, 20); // Calling function 'foo'
}
This is just an example.
The CPU is performing one thread at a specific time. So it can only perform the code in function foo or the function bar, but never both. The scope of the variables in the function are called local or auto variables. They are valid only in the context of the execution of the function. At language level you will say they go out of scope at the closing } bracket. Technically, the memory for the variable is allocated temporarily while entering the function and automatically released on exit. It's just a memory location on the stack. The live time of the variable ends at the end of scope.
So, you must always look at the scope of a variable. You can't access anything temporarily allocated on a different function's stack. The game changes if one function calls another. You can pass a reference from the calling function to the called function, but not the other way.
int foo(int a, int b, int& c, int& d) {
while ( etc. ) {
c = arithmetic_for_c;
d = arithmetic_for_d;
e = c + d;
}
return e;
} // scope of the reference c and ends here,
// but not the scope of the referenced variables.
int bar(a, b) {
int c, d;
// here you define the role of calling function and called function.
int e = foo(a, b, c, d);
cout << e;
cout << c << d;
} // scope of c and d ends here.

Function returning unexpected struct values

I am completely new to structs and user defined datatypes, and i was trying to create a function that returns a struct:
The problem is highlight by the comment:
#include <iostream>
using namespace std;
struct num {
int n[2];
};
num func( num x, int a, int b) {
x.n[0] = a+b;
x.n[1] = a*b;
return x;
}
int main() {
int x,y;
num s1;
cout << "enter: ";
cin >> x >> y;
func(s1,x,y);
cout << s1.n[0] << "\n" << s1.n[1]; // THIS GIVES ERROR
cout << func(s1,x,y).n[0] << "\n" << func(s1,x,y).n[1]; // THIS DOENST GIVE ERROR
return 0;
}
I understand that second method makes sense and returns the struct variable. then putting a dot addresses the inner variable of struct.
But i dont understand why first method fails, or gives odd output. The function has done its job, ie made s1.n[0] = x + y and s1.n[1] = x*y
Now, printing s1.n[0] should print x + y only. How can we check and correct the internal workings of the function?
You have to assign the returned value to the structure object in main
s1 = func(s1,x,y);
Inside the body the function deals with a copy of the original object. It does not change the original object because it is passed by value.
Another approach is to pass the structure by reference
void func( num &x, int a, int b) {
x.n[0] = a+b;
x.n[1] = a*b;
}
In this case in main you could just write
func(s1,x,y);
Or you could use even so-called C approach of passing by reference
void func( num *x, int a, int b) {
x->n[0] = a+b;
x->n[1] = a*b;
}
and call it like
func( &s1, x, y );
As for this statement
cout << func(s1,x,y).n[0] << "\n" << func(s1,x,y).n[1];
then you access data members of two temporary objects returned by the two calls of the function. After executing this statement these temporary objects will be deleted.
It looks like you are never assigning the return value of func(). Your function returns the struct, but you are never assigning it. To fix this, you should be able to simply say: s1 = func(s1,x,y); This will assign the modified version of the struct to the s1 variable.
Alternatively, you could rewrite func() to accept a pointer to the struct. This would allow you to modify the struct without having to return it:
void func( num *x, int a, int b) {
x->n[0] = a+b;
x->n[1] = a*b;
}
Then you would just change your call to func() to say: func(&s1, x, y);
You are not passing your struct by reference, hence the result. Try the following:
void func(num &x, int a, int b) {
x.n[0] = a+b;
x.n[1] = a*b;
}
There's no need for the function to return anything since your struct is passed by reference and it will be changed anyway. Void would fit better.
This is because you have passed the struct by value while your intentions look like you want to pass by reference.
Check this link : http://courses.washington.edu/css342/zander/css332/passby.html
num func( num &x, int a, int b)
should fix your problem

swap with non-const reference parameters

I got [Error] invalid initialization of non-const reference of type 'float&' from an rvalue of type 'float'
#include <stdio.h>
void swap(float &a, float &b){
float temp=a;
a=b;
b=temp;
}
main()
{
int a=10, b=5;
swap((float)a, (float)b);
printf("%d%d",a,b);
}
Vlad is correct, why cast to float? Use int for all values. However, if you have some reason for doing it that way, you must be consistent in your cast and references:
#include <stdio.h>
void swap(float *a, float *b){
float temp=*a;
*a=*b;
*b=temp;
}
int main()
{
int a=10, b=5;
swap((float*)&a, (float*)&b);
printf("\n%d%d\n\n",a,b);
return 0;
}
output:
$ ./bin/floatcast
510
When you pass an address to a function, it must take a pointer as an argument. Thus void swap(float *a,.. When you need a reference to an address of a variable (to pass as a pointer), you use the address of operator &. When you handle values passed as a pointer, in order to operate on the values pointed to by the pointer you must dereference the pointer using the * operator. Putting all that together, you get your code above. (much easier to just use int... :)
C++ Refernce
If I understand what you want in your comment, you want something like this:
#include <iostream>
// using namespace std;
void swap(float& a, float& b){
float temp=a;
a=b;
b=temp;
}
int main()
{
int a=10, b=5;
swap ((float&)a, (float&)b);
std::cout << std::endl << a << b << std::endl << std::endl;
return 0;
}
output:
$ ./bin/floatref
510
You are trying to swap temporary objects (created due to using the casting). that moreover would be deleted after exiting from the swap. You may not bind temporary objects with non-constant references. So there is no sense in such a call. It is entire unclear why you are trying to cast the both integers to float that to swap them. Why do not swap integers themselves?
Write the function like
void swap( int &a, int &b )
{
int temp = a;
a = b;
b = temp;
}
Take into account that there is already standard function std::swap
If you want to write swap function in C then it will look like
void swap( int *a, int *b )
{
int temp = *a;
*a = *b;
*b = temp;
}
You have to get the array using the pointers(*). While passing only you have to give the ampersand(&). Use this following code.
#include <stdio.h>
void swap(int* a, int *b){
float temp=*a;
*a=*b;
*b=temp;
}
main()
{
int a=10, b=5;
swap(&a, &b);
printf("%d \t %d\n",a,b);
}
In C++ you should be using std::swap, or if you prefer you can write your own template that will swap any two values.
template <typename T>
void swap(T & a, T & b)
{
T temp = a;
a = b;
b = temp;
}
int main() {
int a = 10, b = 5;
swap(a, b);
std::cout << a << " \t " << b << std::endl;
return 0;
}
What you are trying to accomplish (treating an int as a float) is going to result in undefined behavior -- it might work on your compiler but it could easily break on a different compiler or architecture. You can use reinterpret_cast to force this behavior if you really want to.

Functions in different files not working properly

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

Unable to change values in a function

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/