swap with non-const reference parameters - c++

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.

Related

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

Reference to pointers Swap in c++

Can someone tell me if my understanding is right ? can someone tell me if the code below is for reference to pointers ?
# include <iostream>
using namespace std;
//function swaps references,
//takes reference to int as input args and swap them
void swap(int& a, int& b)
{
int c=a;
a=b;
b=c;
}
int main(void)
{
int i=5,j=7;
cout<<"Before swap"<<endl;
cout<<"I:"<<i<<"J:"<<j<<endl;
swap(i,j);
cout<<"After swap"<<endl;
cout<<"I:"<<i<<"J:"<<j<<endl;
return 0;
}
You can create a reference to a pointer like this.
int i, j;
int* ptr_i = &i; //ptr_i hold a reference to a pointer
int* ptr_j = &j;
swap(ptr_i, ptr_j);
Function should be,
void swap(int*& a, int*& b)
{
//swap
int *temp = a;
a = b;
b = temp;
}
Note that:
a is the reference for the pointer, ptr_i in the above example.
*a dereferences what ptr_i point to, so you get the variable the
pointer, ptr_i is pointing to.
For more refer this.
In order to modify passing variables to a function, you should use reference (C-style pointers could also be a choice). If your objective is to swap pointers (in your case, addresses of the int variables) you should use reference to pointers and also pass to your swap function pointers (addresses of your int variables)
# include <iostream>
using namespace std;
void swap(int* &a, int* &b)
{
int* c=a;
a=b;
b=c;
}
int main(void)
{
int i=5,j=7;
int * p_i = &i;
int * p_j = &j;
cout << "Before swap" << endl;
cout << "I:" << *p_i << "J:" << *p_j << endl;
swap(p_i,p_j);
cout << "After swap" << endl;
cout << "I:" << *p_i << "J:" << *p_j <<endl;
return 0;
}
I would like to supplement everybody's answers with the standard conforming solution. It is good to know hot things like these work, but I find it better to use std::swap. This also has extra specializations a for containers, and it is generic for any type.
I know that this doesn't answer your question, but it is good to at least know that the standard is there.

C++ Passing pointer to non-static member function

Hi everyone :) I have a problem with function pointers
My 'callback' function arguments are:
1) a function like this: int(*fx)(int,int)
2) an int variable: int a
3) another int: int b
Well, the problem is that the function I want to pass to 'callback' is a non-static function member :( and there are lots of problems
If someone smarter than me have some time to spent, he can look my code :)
#include <iostream>
using namespace std;
class A{
private:
int x;
public:
A(int elem){
x = elem;
}
static int add(int a, int b){
return a + b;
}
int sub(int a, int b){
return x - (a + b);
}
};
void callback( int(*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << fx(a, b) << endl;
}
int main()
{
A obj(5);
//PASSING A POINTER TO A STATIC MEMBER FUNCTION -- WORKS!!
// output = 'Value of the callback: 30'
callback(A::add, 10, 20);
//USING A POINTER TO A NON-STATIC MEMBER FUNCTION -- WORKS!!
int(A::*function1)(int, int) = &A::sub;
// output = 'Non static member: 3'
cout << "Non static member: " << (obj.*function1)(1, 1) << endl;
//PASSING A POINTER TO A NON-STATIC MEMBER FUNCTION -- aargh
// fallita! tutto quello sotto non funziona --> usa i funtori???
// puoi creare una classe wrapper ma non riuscirai mai a chiamare da callback
int(A::*function2)(int, int) = &A::sub;
int(*function3)(int, int) = obj.*function2; //[error] invalid use of non-static member function
callback(function3, 1, 1);
}
There's a way to create my pointer in the way I tried to wrote, like int(*fx)(int, int) = something? I searched a lot but no-one could gave me an answer (well, there was an answer: "NO", but I still think I can do something)
I heard also about functors, may them help me in this case?
Thanks to anyone
PS: sorry for my bad english
EDIT1:
I can use something like this:
template <class T>
void callback2( T* obj, int(T::*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << (obj->*fx)(a, b) << endl;
}
void callback2( void* nullpointer, int(*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << fx(a, b) << endl;
}
and in my main:
callback2(NULL, &mul, 5, 3); // generic function, it's like: int mul(int a, int b){return a*b;}
callback2(NULL, &A::add, 5, 3); //static member function
callback2(&obj, &A::sub, 1, 1); //non static member function
I'm not completely sadisfied, because I don't want to pass my 'callback2' the first parameter (the object)...
The question, for people that didn't understand my (bad) explanation, is: can I delete the first parameter in my callback2 function?
the prototype will be
void callback2(int(*fx)(int, int), int a, int b)<br>
and I will call like this:
callback2(&obj.sub, 1, 3);
Functions cannot be referenced this way:
int (*function3)(int, int) = obj.*function2;
You have to pass the address of the function like this:
int (*function3)(int, int) = std::mem_fn(&A::sub, obj);
// ^^^^^^^^^^^^^^^^^^^^^^^^^
The expression function2 decays into a pointer-to-function which allows it to work.
I would do it with std functors, here is a simple example based off of your code:
#include <iostream>
#include <functional>
using namespace std;
class A{
private:
int x;
public:
A(int elem){
x = elem;
}
static int add(int a, int b){
return a + b;
}
int sub(int a, int b) const{
return x - (a + b);
}
};
void callback( std::function<int(const A& ,int,int )> fx, A obj, int a, int b)
{
cout << "Value of the callback: " << fx( obj, a, b) << endl;
}
int main()
{
A obj(5);
std::function<int(const A& ,int,int )> Aprinter= &A::sub;
callback(Aprinter,obj,1,2);
}

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

Can I cast an array like this?

Example code:
#include <cstdlib>
#include <iostream>
using namespace std;
class A {
public:
A(int x, int y) : x(x), y(y) {}
int x, y;
};
class B {
public:
operator A() {
return A(x,y);
}
float x, y;
};
void func1(A a) {
cout << "(" << a.x << "," << a.y << ")" << endl;
}
void func2(A *a, int len) {
for(int i=0; i<len; ++i) {
cout << "(" << a->x << "," << a->y << ")";
}
cout << endl;
}
int main(int argc, char** argv) {
B b[10];
func1(b[0]);
//func2(b, 10);
return(EXIT_SUCCESS);
}
func1 works as expected, but func2 throws a compile-time error. Is there anything I can add to class B to make this work? I suspect not, but it doesn't hurt to ask, right?
I assume it won't work because the size of A is different from the size of B?
void func2(A *a, int len)
When you try to pass a pointer of type B to func2 there is no acceptable conversion from B* to A*. These are two different types from A and B, though the type B has a conversion operator to type A.
When you pass array to a method you are only passing the address of the first element not the actual copy of the array nor the first element.
In func1 you pass first element of array which is object of class B. Because B has operator A() it can convert B to A and new object of class A is passed to func1
In func2 you pass pointer to an array of B objects which is not the same as array of A objects so you get error.
To solve it you could have a transformation method that takes pointer to array of B's and iterators over it and for each calls func1 or something like that.
The other answers have addressed the core issue. But for completeness, it's worth noting that
I assume it won't work because the
size of A is different from the size
of B?
is incorrect.
First, A and B as given in this example would actually be the same size on many current compilers.
But even when A and B are the same size, the compiler will not perform this kind of conversion automatically. In fact, even if they have the exact same memory layout of member variables, the compiler will still not do it.