I have two basic Cpp tasks, but still I have problems with them. First is to write functions mul1,div1,sub1,sum1, taking ints as arguments and returning ints. Then I need to create pointers ptrFun1 and ptrFun2 to functions mul1 and sum1, and print results of using them. Problem starts with defining those pointers. I thought I was doing it right, but devcpp gives me errors in compilation.
#include <iostream>
using namespace std;
int mul1(int a,int b)
{
return a * b;
}
int div1(int a,int b)
{
return a / b;
}
int sum1(int a,int b)
{
return a + b;
}
int sub1(int a,int b)
{
return a - b;
}
int main()
{
int a=1;
int b=5;
cout << mul1(a,b) << endl;
cout << div1(a,b) << endl;
cout << sum1(a,b) << endl;
cout << sub1(a,b) << endl;
int *funPtr1(int, int);
int *funPtr2(int, int);
funPtr1 = sum1;
funPtr2 = mul1;
cout << funPtr1(a,b) << endl;
cout << funPtr2(a,b) << endl;
system("PAUSE");
return 0;
}
38 assignment of function `int* funPtr1(int, int)'
38 cannot convert `int ()(int, int)' to `int*()(int, int)' in assignment
Task 2 is to create array of pointers to those functions named tabFunPtr. How to do that ?
Instead of int *funPtr1(int, int) you need int (*funPtr1)(int, int) to declare a function pointer. Otherwise you are just declaring a function which returns a pointer to an int.
For an array of function pointers it's probably clearest to make a typedef for the function pointer type and then declare the array using that typedef.
E.g.
funPtr_type array_of_fn_ptrs[];
This int *funPtr1(int, int); declares a function.
This int (*funPtr1)(int, int);defines a function pointer.
This typedef int (*funPtr1)(int, int); defines a function pointer type.
If you think that's confusing, try to define a pointer to a function which returns an array of pointers to member functions... C's declaration syntax is a nightmare.
Related
//libraries
#include <iostream>
//standard namepace
using namespace std;
int Car() {
int a;
int b;
cout << "Fuel Tank" << endl;
cin >> a;
cout << "MPG" << endl;
cin >> b;
return a, b;
}
int main() {
int a;
int b;
a,b = Car();
cout << "Print Values " << (a,b); // <--- Line 25
return 0;
}
Let's say you put 10 and 15 as the first and second input. Why is 15 the only variable to print in the cout statement on line 25.
That's not how C++ works.
You need:
std:: pair<int, int> Car() {
...
return {a, b};
}
auto [a, b] = Car();
std::cout << a << ", " << b;
What you have:
int Car()
Car is a function which returns 1 int.
return a, b;
Here you have the comma operator which evaluates every argument and discards all but the last one. So it returns b.
a, b = Car();
(a, b)
Again the comma operator. a is discarded and b is assigned. Then a is discarded and b is printed.
Unlike Python, C++ does not have a built in notion of a tuple. Your Car function is declared to return a single integer, and so one integer you will get. An alternative is to use std::pair<int, int> in #include <utility> like so:
std::pair<int, int> Car() {
// ...
return std::make_pair(a, b);
}
I assume the program compiles because in C/C++, the comma separated expression list as you wrote is evaluated in order and only the last expression or item in that list is returned. So your first Car() function returns the last integer b, and you only initialize b in your assignment in main() to that other b. Likewise, your cout only prints b, hence 15.
What I would recommend doing is making the function a void and passing the variables by reference. When you pass the variables by reference, you can change their value in the function and they will not be lost due to scope. This is because passing by reference references the location in memory where that variable is stored, instead of creating a copy like passing by value does (which you did).
#include <iostream>
using namespace std;
void car(int &a, int &b); // function prototype calling for a and b to be passed by
// reference
int main()
{
int a = 0;
int b = 0;
car(a, b);
cout << "Print Values " << a << " " << b;
return 0;
}
void car(int &a, int &b)
{
int temp = 0;
cout << "Fuel Tank" << endl;
cin >> a;
cout << "MPG" << endl;
cin >> b;
}
As you see, instead of returning values, the function changes the values of the variables by accessing their location.
Edit: Typically, functions will go below main and you have prototypes for the functions above main (as seen in my example).
Another thing, you named the function, "Car();". Typically, functions start with the first word as a lowercase letter with the following words capitalized. This makes it easier to not confuse them with constructor function names for classes, in which the first letter of the first word is usually capitalized.
#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;
}
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.
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.
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);
}