Calling function to add one to a number in C - c

Here is what I am trying to do:
-Have a variable call_count, an integer initialized to zero
-Call functions f1 and f2 several times
-Output the final value of call_count
-Two functions, f1, and f2 that when called
cause call_count to increment by 1
This is what I could do so far but when I compile and run this, it still outputs 0. What am I doing wrong? Thanks for the help.
Question edit: How can I use a pointer here to accomplish this?
#include <stdio.h>
void f1(int call_count){ call_count = call_count + 1;}
void f2(int call_count){ call_count = call_count + 1;}
int main(){
int call_count = 0;
f1(call_count);
f2(call_count);
printf("%d",call_count);
}

you are sending a copy of call_count to functions f1 and f2 , in C by default called by value method will be used.
The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
you have to way to do what you want :
you can return call_count.
using pointers which means call by reference.
since you want to use pointers to accomplish this:
void f1(int *call_count) { *call_count = *call_count + 1; }
void f2(int *call_count) { *call_count = *call_count + 1; }
int main() {
int call_count = 0;
f1(&call_count);
f2(&call_count);
printf("%d", call_count);
}

Because you lost the value in the memory, you have two solutions :
1 you should use pointer :
int main()
{
void f1(int*call_count){ *call_count = *call_count + 1;}
void f2(int*call_count){ *call_count = *call_count + 1;}
int call_count=0;
f1(&call_count);
f2(&call_count);
printf("%d",call_count);
}
Or you change the function type : int instead of void
int main()
{
int f1(int call_count){ return call_count + 1;}
int f2(int call_count){ return call_count + 1;}
int call_count=0;
int result1=f1(call_count);
int result2=f2(result1);
printf("%d",result2);
}
If you don't know how pointer works in your case, you have to use the solution 2

Related

Why does this code won't work? It displays 0

Whenever I compile it displays 0 instead of 11. what is wrong this code? I used a function add. I notice that this works when I'm using an array string.
#include <stdio.h>
#include <stdlib.h>
void add(int result, int a, int b);
int main(void) {
int num1 = 5;
int num2 = 6;
int result1 = 0;
add(result1, num1, num2);
printf("%d", result1);
return 0;
}
void add(int result, int a, int b) {
result = a + b;
}
Arguments of C functions are copies of what are passed, so modifying them in callee will not affect what is passed in caller.
To have functions modify passed things, you should pass pointers to what should be modified.
#include <stdio.h>
void add(int *result, int a, int b); /* add * to make result a pointer */
int main(void) {
int num1 = 5;
int num2 = 6;
int result1 = 0;
add(&result1, num1, num2); /* add & to pass a pointer */
printf("%d", result1);
return 0;
}
void add(int *result, int a, int b) { /* add * to make result a pointer */
*result = a + b; /* add * to dereference the pointer */
}
Because the changes done by the operation performed inside the method add in not visible outside. Those arguments that you have passed are being pass by value
Pass by Value
Pass by Value, means that a copy of the data is made and stored by way
of the name of the parameter. Any changes to the parameter have NO
affect on data in the calling function.
To made those changes visible to the outside you can pass the memory reference of the result variable (i.e., pass-by-reference)
Pass by Reference
A reference parameter "refers" to the original data in the calling
function. Thus any changes made to the parameter are ALSO MADE TO THE
ORIGINAL variable.
For example:
void add(int *result, int a, int b) {
*result = a + b;
}
and call the in the main as follows:
add(&result1, num1, num2);
or return the result of the operation as follows :
int add(int a, int b) {
return a + b;
}
and call it in the main as follows:
result1 = add(num1, num2);

Passing function to function C [duplicate]

I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?
Declaration
A prototype for a function which takes a function parameter looks like the following:
void func ( void (*f)(int) );
This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:
void print ( int x ) {
printf("%d\n", x);
}
Function Call
When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:
func(print);
would call func, passing the print function to it.
Function Body
As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:
void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
Source
This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.
typedef void (*functiontype)();
Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:
void dosomething() { }
functiontype func = &dosomething;
func();
For a function that returns an int and takes a char you would do
typedef int (*functiontype2)(char);
and to use it
int dosomethingwithchar(char a) { return 1; }
functiontype2 func2 = &dosomethingwithchar
int result = func2('a');
There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!
boost::function<int (char a)> functiontype2;
is so much nicer than the above.
Since C++11 you can use the functional library to do this in a succinct and generic fashion. The syntax is, e.g.,
std::function<bool (int)>
where bool is the return type here of a one-argument function whose first argument is of type int.
I have included an example program below:
// g++ test.cpp --std=c++11
#include <functional>
double Combiner(double a, double b, std::function<double (double,double)> func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
Sometimes, though, it is more convenient to use a template function:
// g++ test.cpp --std=c++11
template<class T>
double Combiner(double a, double b, T func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
Pass address of a function as parameter to another function as shown below
#include <stdio.h>
void print();
void execute(void());
int main()
{
execute(print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void f()) // receive address of print
{
f();
}
Also we can pass function as parameter using function pointer
#include <stdio.h>
void print();
void execute(void (*f)());
int main()
{
execute(&print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void (*f)()) // receive address of print
{
f();
}
Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:
void foo(int bar(int, int));
is equivalent to this:
void foo(int (*bar)(int, int));
I am gonna explain with a simple example code which takes a compare function as parameter to another sorting function.
Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.
Compare Function
bool compare(int a, int b) {
return a > b;
}
Now , the Bubble sort that takes another function as its parameter to perform comparison
Bubble sort function
void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {
for (int i = 0;i < n - 1;i++) {
for (int j = 0;j < (n - 1 - i);j++) {
if (cmp(arr[j], arr[j + 1])) {
swap(arr[j], arr[j + 1]);
}
}
}
}
Finally , the main which calls the Bubble sort function by passing the boolean compare function as argument.
int main()
{
int i, n = 10, key = 11;
int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };
bubble_sort(arr, n, compare);
cout<<"Sorted Order"<<endl;
for (int i = 0;i < n;i++) {
cout << arr[i] << " ";
}
}
Output:
Sorted Order
3 6 8 11 12 12 15 18 20 22
You need to pass a function pointer. The syntax is a little cumbersome, but it's really powerful once you get familiar with it.
typedef int function();
function *g(function *f)
{
f();
return f;
}
int main(void)
{
function f;
function *fn = g(f);
fn();
}
int f() { return 0; }
It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do.
#include <stdio.h>
int IncMultInt(int a, int b)
{
a++;
return a * b;
}
int main(int argc, char *argv[])
{
int a = 5;
int b = 7;
printf("%d * %d = %d\n", a, b, IncMultInt(a, b));
b = 9;
// Create some local code with it's own local variable
printf("%d * %d = %d\n", a, b, ( { int _a = a+1; _a * b; } ) );
return 0;
}

Accessing array of function pointers

Following is the array of function pointers
(int) (*a[5]) (int);
int f1(int){};
...
is the following way of definition correct?
a = f1;
a + 1 = f2;
a + 2 = f3;
...
how do we call these functions?
*a(1) // is this correct???
*(a+1) (2)
#include <stdio.h>
int f1(int i) { return i; }
int f2(int i) { return i; }
int main() {
int (*a[5]) (int);
a[0] = f1;
a[1] = f2;
printf("%d\n", a[0](2));
printf("%d\n", a[1](5));
}
What you call "definition" is just assignment, and as you are doing it, it is wrong, since you can't assign to arrays in C. You can only assign to individual array elements, correct would be a[0] = f1 etc.
Often for arrays of function pointers there is no need to assign them dynamically at run time. Function pointers are compile time (or link time) constants anyhow.
/* in your .h file */
extern int (*const a[5]) (int);
/* in your .c file */
int (*const a[5]) (int) = { f1, f2, f3 };
To simplify using function pointers a bit, the identifier for a f1 is equivalent to a pointer to the function &f1 and using a function pointer with parenthesis as in a[0](5) is the same as dereferencing the pointer and calling the resulting function (*(a[0]))(5).
you can write:
a[0]=&f1;
and call it as below:
a[0](1);
note that there is no need to use a pointer while the function is getting called.
If you insist on using a pointer, then you can anyhow do the below:
(*a[0])(1);
It is always better to use typedefs, (and all your functions need to have a common interface anyway and also to initialise at declaration time, where possible function arrays should also be const as a safety measure so:
#include <stdio.h>
typedef int (*mytype)();
int f1(int i) { return i; }
int f2(int i) { return i; }
int main() {
const mytype a[5] = {f1,f1,f2,f2,f1};
printf("%d\n", a[0](2));
printf("%d\n", a[1](5));
return 0;
}
#include<stdio.h>
int (*a[5]) (int);
int f1(int i){printf("%d\n",i); return 0;}
int f2(int i){printf("%d\n",i); return 0;}
int f3(int i){printf("%d\n",i); return 0;}
int main(void)
{
a[0] = f1; // Assign the address of function
a[1] = f2;
a[2] = f3;
(*a[0])(5); // Calling the function
(*a[1])(6);
(*a[2])(7);
getchar();
return 0;
}

Using variables

I have a problem with this simple program because it doesnt give me the true outcome. I just want to sum two arguments in the first function and then use the outcome in the second one. It will be nice to have overall outcome in the main function. Also I would like to ask the same question with arrays.
#include <stdio.h>
#include <stdlib.h>
int sum()
{
int a=2;
int b=3;
int s=a+b;
printf("sum=%d\n",s);
return s;
}
int sum2(int s)
{
int c=5;
int d=c+s;
}
int main(int s,int d)
{
sum();
printf("sum=%d\n",s);
printf("sum2=%d\n",d);
getchar();
return 0;
}
There are many problems with this code:
int main(int s, int d) won't do what you think. Command-line arguments to your program come in string format. So you would need to use int main(int argc, char *argv[]).
The variables s and d in main() are completely independent to the variables in sum() and sum2(). So changing their values in those functions will not affect the original variables.
You're not even calling the second function!
You can do things like this:
int sum(int a, int b)
{
return a+b;
}
int sum2(int c)
{
return c+5;
}
int main(void)
{
int x = 2;
int y = 3;
int z = sum(x,y);
int w = sum2(z);
printf("z = %d\n", z);
printf("w = %d\n", w);
}
First of all, s is a local variable inside sum( ). Hence it cannot be available outside the function.
int sum() {
// ..
int s = a+b; // local variable, hence local scope
// ..
}
Also, secondly, int main(int s,int d) won't work since in command line arguments come in String format. So can't use a int there
I won't tell you the answer (lol but others have) but I'll give you these clues to figuring it out.
Ask your self which functions are returning data and which ones aren't.
Clue: the function needs a return to return some data.
Then ask yourself which functions' returns are actually being used.
Clue: to collect the data returned from a function you need to assign the result to a variable like so
int i;
i = somefunct();
You can't access the value of variable 's' outside the function sum() since it is out of scope. You'll have to return the value to your main() function. Also your main function parameters are incorrect. You need something more like this:
#include <stdio.h>
#include <stdlib.h>
int sum(int a, int b)
{
int s=a+b;
printf("sum=%d\n",s);
return s;
}
int sum2(int c, int sum)
{
return c+sum;
}
int main(int argc, char *argv[])
{
int val1 = sum(2, 3);
printf("sum=%d\n",val1);
int val2 = sum2(5, val1);
printf("sum2=%d\n", val2);
getchar();
return 0;
}

How do you pass a function as a parameter in C?

I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?
Declaration
A prototype for a function which takes a function parameter looks like the following:
void func ( void (*f)(int) );
This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:
void print ( int x ) {
printf("%d\n", x);
}
Function Call
When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:
func(print);
would call func, passing the print function to it.
Function Body
As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:
void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
Source
This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.
typedef void (*functiontype)();
Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:
void dosomething() { }
functiontype func = &dosomething;
func();
For a function that returns an int and takes a char you would do
typedef int (*functiontype2)(char);
and to use it
int dosomethingwithchar(char a) { return 1; }
functiontype2 func2 = &dosomethingwithchar
int result = func2('a');
There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!
boost::function<int (char a)> functiontype2;
is so much nicer than the above.
Since C++11 you can use the functional library to do this in a succinct and generic fashion. The syntax is, e.g.,
std::function<bool (int)>
where bool is the return type here of a one-argument function whose first argument is of type int.
I have included an example program below:
// g++ test.cpp --std=c++11
#include <functional>
double Combiner(double a, double b, std::function<double (double,double)> func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
Sometimes, though, it is more convenient to use a template function:
// g++ test.cpp --std=c++11
template<class T>
double Combiner(double a, double b, T func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
Pass address of a function as parameter to another function as shown below
#include <stdio.h>
void print();
void execute(void());
int main()
{
execute(print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void f()) // receive address of print
{
f();
}
Also we can pass function as parameter using function pointer
#include <stdio.h>
void print();
void execute(void (*f)());
int main()
{
execute(&print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void (*f)()) // receive address of print
{
f();
}
Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:
void foo(int bar(int, int));
is equivalent to this:
void foo(int (*bar)(int, int));
I am gonna explain with a simple example code which takes a compare function as parameter to another sorting function.
Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.
Compare Function
bool compare(int a, int b) {
return a > b;
}
Now , the Bubble sort that takes another function as its parameter to perform comparison
Bubble sort function
void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {
for (int i = 0;i < n - 1;i++) {
for (int j = 0;j < (n - 1 - i);j++) {
if (cmp(arr[j], arr[j + 1])) {
swap(arr[j], arr[j + 1]);
}
}
}
}
Finally , the main which calls the Bubble sort function by passing the boolean compare function as argument.
int main()
{
int i, n = 10, key = 11;
int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };
bubble_sort(arr, n, compare);
cout<<"Sorted Order"<<endl;
for (int i = 0;i < n;i++) {
cout << arr[i] << " ";
}
}
Output:
Sorted Order
3 6 8 11 12 12 15 18 20 22
You need to pass a function pointer. The syntax is a little cumbersome, but it's really powerful once you get familiar with it.
typedef int function();
function *g(function *f)
{
f();
return f;
}
int main(void)
{
function f;
function *fn = g(f);
fn();
}
int f() { return 0; }
It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do.
#include <stdio.h>
int IncMultInt(int a, int b)
{
a++;
return a * b;
}
int main(int argc, char *argv[])
{
int a = 5;
int b = 7;
printf("%d * %d = %d\n", a, b, IncMultInt(a, b));
b = 9;
// Create some local code with it's own local variable
printf("%d * %d = %d\n", a, b, ( { int _a = a+1; _a * b; } ) );
return 0;
}

Resources