Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
In this Program, I am unable to understand the declaration of the "sum" function.
Please explain what is happening while calling the sum function and while declaring the function.
#include<iostream.h>
#include <conio.h>
int sum(int(*)(int),int);
int square(int);
int cube(int);
void main()
{
clrscr();
cout<<sum(square,4)<<endl;
cout<<sum(cube,4)<<endl;
getch();
}
int sum(int(*ptr)(int k),int n)
{
int s=0;
for(int i=1;i<=n;i++)
{
s+=(*ptr)(i);
}
return s;
}
int square(int k)
{
int sq;
sq=k*k;
return k*k;
}
int cube(int k)
{
return k*k*k;
}
The parameter is a function pointer - you should read here for an introduction, and heres a relevant SO post.
The idea is that you can pass around a function as a value - so you can make other general functions that you can give a specific function to in order to change the effect. An example would be map from functional programming.
Specifically in your case, the sum function takes this function pointer in order to sum a function of the values in the list given to it, rather than just the values themselves. This is demonstrated by passing it eg. a pointer to the square function, which will make it sum squares of the values given to sum.
This is the reason why some people does not like pointers in C and C++. See my explanation below in your program:-
#include<iostream.h>
# include <conio.h>
void main()
{
clrscr();
int sum(int(*)(int),int);// Here first parameter in `sum` is a pointer to a function which return type is int. `int(*)(int)` here int(*) is function pointer and (int) is its parameter type.
int square(int);
int cube(int);
cout<<sum(square,4)<<endl;// Now you are passing address of function `square` as first parameter and its parameter 4, like square(4)
cout<<sum(cube,4)<<endl; // Here you are passing address of function `cube` as parameter and 4 as parameter to cube function
getch();
}
int sum(int(*ptr)(int k),int n)
{
int s=0;
for(int i=1;i<=n;i++)
{
s+=(*ptr)(i); //This `ptr` is nothing but the address of function passed to sum
//hence it execute like below
//When you are calling function `sum` with function pointer `square` as first parameter
//it execute like `s = s + square(i);`
//Now at the second call to `sum` it execute like `s = s + cube(i);`
}
return s;
}
// The method sum
// First argument: a pointer to a function which accepts one integer
// as argument and returns an integer
// Second argument: an integer
int sum(int(*)(int),int);
That is why when you call sum in this line:
cout<<sum(square,4)<<endl;
You pass square as the first argument and since square is like this:
int square(int k)
{
}
it satisfies the call because it is a function which accepts one integer as argument and returns int.
Then inside the sum method, it calls the function which you passed in as the first argument like this (please read my comments inline for clarity):
int sum(int(*ptr)(int k),int n)
{
int s=0;
for(int i=1;i<=n;i++)
{
// Calls the function pointer (square in this case) and sends i to
// it as argument. It then takes the return value and adds it to s.
s+=(*ptr)(i);
}
return s;
}
Here are the different parts:
Here is another example to help you:
// fcnPtr is a pointer to a function that takes no arguments and returns an integer
int (*fcnPtr)();
Related
I got this declaration from https://en.cppreference.com/w/cpp/language/scope, but don't know how to parse this declaration even there is a comment below.
my questions is
how to parse the declaration statement (I see it as a function pointer to a function protocol like "int[3] foo(int n)" or "int foo(int n)[3] --- they are illegal in C++ )? Then, how can I construct a concrete function which can be assigned to this function pointer? Thanks.
const int n = 3;
int (*(*f2)(int n))[n]; // OK: the scope of the function parameter 'n'
// ends at the end of its function declarator
// in the array declarator, global n is in scope
// (this declares a pointer to function returning a pointer to an array of 3 int
It's a pointer to a function taking an int and returning a pointer to an int array of size three.
All the comment is saying is that there are two n identifiers in play here. The [n] (in array declarator) is using the const int 3, not the parameter to the function (which is in the function declarator).
Starting in the middle, with each segment being included in the subsequent bullet point as ...:
f2 is a pointer, (*f2).
It's a pointer to a function taking an integer, ...(int).
It returns a pointer to an int array of size three, int (*...)[3].
You can form a concrete function for it as per the following complete program, which output the first element, 42:
#include <iostream>
const int n = 3;
int (*(*f2)(int n))[n];
int (*g2(int))[n] {
static int x[::n] = { 42 }; // Use outer n, not the parameter.
return &x; // since C++ has no VLAs. This
// means parameter is not actually
// needed in this test case, though
// it may be in more complicated
// tests.
}
int main() {
f2 = &g2; // Assign concrete function to pointer.
auto y = f2(3); // Call via pointer, get array.
std::cout << *(y[0]) << '\n'; // Deref first element to get 42.
}
Having said that, I would be rather curious if one of my colleagues submitting something like that for a code review, at least without a large comment explaining it. Although seasoned developers may be able to work it out, those less experienced may have trouble.
And, in fact, even seasoned developers shouldn't have to work it out, especially given it took me a few minutes.
C++ has a very expressive type system which can easily build something like this up in parts, so you don't have to experience migraines trying to work it out. For something like this, I'd be using std::vector (or std::array) unless there was a compelling case for the added complexity caused by more basic types.
You can create a type for pointer to an array of 3 int
typedef int (*array_with_size_n)[n];
and then use it as return type
const int n = 3;
int (*(*f2)(int n))[n];
int arr[n];
array_with_size_n func(int n)
{
return &arr;
}
int main()
{
f2 = &func;
return 0;
}
I am a newbie programmer in c++ started my Computer Science degree. I got a problem with my assignment.
You need to make a function char calculate_daily_sale(int []).
You need to define and read an array of integer values of length 10 in the main() function.
Write a function charcalculate_daily_sale (int []) that accepts the array as argument from the main() function. The function will sum the values of array. If the values are greater than or equal to 15,000 the
function return āyā back to the main function, otherwise ānā is returned from the function.
This is the code that I managed to write:
#include <iostream>
using namespace std;
char calculate_daily_sale(int[])
{
int arr[10];
int *ptr[10];
int sum=0;
for(int j=0; j<=9; j++)
{
ptr[j]=&arr[j];
sum=sum+arr[j];
cout<<sum;
}
}
int main()
{
int n,y;
int arr[10];
int *ptr[10];
for(int i=0; i<=9; i++)
{
ptr[i]=&arr[i];
cin>>*ptr[i];
}
if(calculate_daily_sale(int[])>=15000)
{
return y;
}
else
{
return n;
}
return 0;
}
The error that I am getting is:
expected primary expression before 'int'
You need to take a step back and learn the basics of C++ programming.
Some points you should be looking at are:
char calculate_daily_sale(int[])
The function has a return type of 'char' and therefore needs a return statement.
The function parameter is not named and not used. It can be removed entirely.
if(calculate_daily_sale(int[])>=15000)
When calling a function, you need to pass a value, not a type 'int[]'
The return type of is char so it seems odd to be comparing it with 15000.
return y and return n
n and y are uninitialized.
A value returned from main is simply an error code returned to the operating system that runs the programme. It seems unlikely that you want to return these numbers, whatever they are. My reading of the spec is that you need to be returning the characters 'n' and 'y' (for 'yes' and 'no') from your calculate_daily_sale and to main, which is why the return type is char.
Error messages always mention line number. This is the way you can locate the error precisely. Assuming your error is in this line
if(calculate_daily_sale(int[])>=15000)
You probably meant to pass the array arr to calculate_daily_sale:
if(calculate_daily_sale(arr)>=15000)
I am newbie in c++ and just learning it.
I have written the following code.
#include<iostream>
#include<cstdio>
using namespace std;
void first(int &x,int n)
{
int i;
for(i=0;i<n;i++)
{
cout<<x+i;
}
cout<<endl;
}
void second(int *x,int n)
{
int i;
for(i=0;i<n;i++)
{
cout<<*x+i;
}
cout<<endl;
}
int main()
{
int exm[5]={1,2,3,4,5};
first(exm[0],5);
second(exm,5);
return 0;
}
this program gives output correctly.but the problem is i don't understand the differences between using & and * in function parameters...
both are the techniques of passing arguments by references and when we pass by reference we just send the memory address...
but in function first when i tried to call the function as follows
first(exm,5);
function occurred an error.
why ?
but when i called the function as follows
first(exm[0],5);
it compiled properly and gave right output...but i know that the both calling is equivalent...
then why this error occured?
what is the difference between using & and * in function parameters?
The type of the variable exm is int[5], which doesn't meet the signature of first(int &x,int n).
But int[N] can be converted implicitly to int* that points to the first element of the array, hence second(exm,5) can compile.
what is the difference between using & and * in function parameters?
It's the difference between a reference and a pointer.
There are lots of differences between them.
In this case, I think the biggest difference is whether it accepts NULL or not.
See:
- What are the differences between a pointer variable and a reference variable in C++?
- Are there benefits of passing by pointer over passing by reference in C++?
- difference between a pointer and reference parameter?
I can't understand one weird thing. Here is my program :
#include <iostream>
using namespace std;
void Swap(int *a , int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int a=0;
int b=0;
cout<<"Please enter integer A: ";
cin>>a;
cout<<"Please enter integer B: ";
cin>>b;
cout<<endl;
cout<<"************Before Swap************\n";
cout<<"Value of A ="<<a<<endl;
cout<<"Value of B ="<<b<<endl;
Swap (&a , &b);
cout<<endl;
cout<<"************After Swap*************\n";
cout<<"Value of A ="<<a<<endl;
cout<<"Value of B ="<<b<<endl;
return 0;
}
Now if you look at the function "Swap", I have used "void Swap". Therefore it must not return any value to main function (only "int" returns a value (at least that's what my teacher has taught me)). But if you execute it, the values are swaped in main function! How come ? Can anyone tell me how its possible ?
Swap function in your example just swaps two integers, but does NOT return anything.
In order to check what function has retuned, you have to assign it to some variable, like this
int a = swap(&a, &b);
but this piece of code has an error because swap function doesn't return anything.
Another example:
int func() {
return 18;
}
int main() {
int a = func();
cout << a;
}
Is fine, cause variable a is int and function func returns an int.
Swap may not return any values, but it can still modify them. You're passing in pointers to two variables into the function. If you change the value the pointer maps to in the Swap function, that change persists throughout the program.
Actually, the function is NOT returning the value. It is just accessing the values through the variables' addresses and swapping them from their reference. Your code is right and now I have cleared your concept without any long explanation. That's all.
This is correct.
Your Swap method does work with pointers, not real values.
In your main your are calling this method and tell it to swap the values in the variables. They are in the sme context at this point.
Your code looks very similar to this:
http://www.tutorialspoint.com/cplusplus/cpp_function_call_by_pointer.htm
What it does it uses pointers addresses. You use them as parameters and then you use them to access the information stored at that location, which is the values of a and b, and then change them.
I think you are misunderstand what your teacher said.
What he/she said might be Swap() will not return value, but change value by passing address is still valid.
like this:
int Swap();
int GetReturnValue = Swap(); // Get return value from Swap()
Let's look the second one:
void Swap();
int GetReturnValue = Swap();
Though the second one might really get value, but this value is meaningless.
Sometimes, you will get a compiler warning if you do like the second one, GCC Compiler will report warnings about casting
Swap procedure can only modify your variables because you've passed them by reference.
Remember procedures, unlike functions, cannot return a value.
EDIT: thanks for all the speedy responses, I have a much better understanding of this concept now. Also, I'll try to make my error messages more clear next time.
EDIT: updated with my newest code. the error happens on line 18. Also, I'm beginning to wonder if my latest issue has to do with the original class itself?
I'm trying to teach myself classes and objects in C++. I did it once by just declaring a void function, outputting something on the screen, calling the object in main and everything worked fine.
Now, I wanted to expand upon this and make a simple addition thing. However, I get a couple errors on Code Blocks:
error: invalid use of non-static member function 'int Addition::add(int, int)'
error: no matching function for call to 'Addition::add()'
Here's my code:
#include <iostream>
using namespace std;
class Addition {
public:
int add (int x, int y) {
int sum;
sum=x+y;
return sum;
}
};
int main()
{
int num1;
int num2;
int ans=addobj.add(num1,num2);
Addition addobj;
addobj.add(num1,num2);
cout<<"Enter the first number you want to add"<<endl;
cin>>num1;
cout<<"Enter the second number you want to add"<<endl;
cin>>num2;
cout<<"The sum is "<<ans<<endl;
}
One of the most important things, a developer should learn to do is to read compiler's messages. It's clear enough:
error: no matching function for call to 'Addition::add()'
Your function in your class is
int add (int x, int y)
it takes 2 arguments and you pass none:
addobj.add();
You have 2 options:
create and initialize x and y inside your main and pass them as arguments
make add without parameters, create x and y inside add's body, as their values are taken from user input.
In this case, as the function's name is add, I'd chose the first option:
declare int x, y; inside your main
read the user input inside the main (the part, where you use cin and cout)
pass the x and y as arguments to add like this: addobj.add( x, y );
store the result (if needed), like this: int result = addobj.add( x, y );
You declared a method add(int, int) that takes two integers as arguments; you have to supply those arguments when you call it. It would be nice to print the returned value, as well:
Addition addobj;
std::cout << addobj.add(1, 2) << std::endl;
Your add function takes two arguments, yet you call it with none, so no matching function could be found. You must call the function as it was declared, i.e.,
addobj.add(1, 2);
Your function takes two arguments and yet you call it without providing them. You need to provide the two integer arguments that your function requires. To be useful you should store the result too. Something like this
int a = 1;
int b = 2;
int result = addjobs.add(a,b);