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);
Related
I have a quastion about C functions. Is there any possibility to do something like:
#define PRINT_SUM_OF_CONSTS() printSum(10, 5)
void printSum(int a, int b){
print("%d + %d = %d", a, b, a+b);
}
int main(){
void (*pFunc)(void);
pFunc = &PRINT_SUM_OF_CONSTS;
pFunc();
return 0;
}
What I need is to use function which takes two arguments, asign arguments to constants with a macro and use it as function without arguments. Is that somehow possible?
pFunc is a pointer to a function, you cannot create a pointer to a function call with specific parameters.
However, the solution is simple and does not require a macro - you simply create a wrapper function that calls the target function with the desired parameters:
#include <stdio.h>
void printSum(int a, int b)
{
printf("%d + %d = %d", a, b, a+b);
}
void printSumConst() { printSum(10, 5) ; }
int main()
{
void (*pFunc)(void) = printSumConst;
pFunc();
return 0;
}
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
I have a function which returns an integer pointer type:
int* f(int a, int b){
int *result;
result = &a;
*result += b;
return result;
}
and when I call this on main:
int main(){
int a = 5;
int b = 2;
int *result = f(a,b);
printf("The result is: %d \n", *result);
return 0;
}
It gives me the correct output(in this case 7). I was under the impression that by assigning the address of the parameter a to result I would get a segmentation fault when I ran this function.
My assumption is that C treats function parameters as local in scope to the function definition. But, I see that this is not the case so why is this specific program working ?
I'm using Code::Blocks 16.01 with gcc compiler.
Just because it works on your machine doesn't mean it isn't undefined behaviour. This works by fluke, but it's invalid.
It may produce the correct result because that stack is not overwitten or otherwise mangled by the time you do something later on.
For example, if you make another function call:
#include <stdio.h>
#include <stdlib.h>
int noop(int x, int y) {
return x + y;
}
int* f(int a, int b){
int *result;
result = &a;
*result += b;
return result;
}
int main(){
int a = 5;
int b = 2;
// Do something with undefined behaviour
int *result = f(a,b);
// Do something else which uses the stack and/or the same memory
int x = 10;
int y = 11;
int z = noop(x, y);
printf("The result is: %d \n", *result);
return 0;
}
Now the output gets stomped with the definition of x which coincidentally takes the same piece of memory so the output is 10. As this is undefined behaviour, though, anything could happen, including a crash.
int main ()
{
int a, b;
call(&b);
printf("%d, %d",a , b);
}
void call(int *ptr)
{
}
Desired output:
50, 100
How to write the call function so as to modify both the variables to get the desired output??
Not sure where the values 50 and 100 are coming from or exactly what you are asking but maybe this will help with your question.
Since C is pass by value you need to send pointers to actually change the value inside another function.
Since the call function will have pointer values you need to dereference the pointers before changing the value.
Here is an example:
void call(int *a, int *b)
{
*a = 50;
*b = 100;
}
int main()
{
int a, b;
call(&a, &b);
printf("%d, %d\n", a, b);
}
While we are exploring the many ways this output could be achieved, consider that the function could store state in a static variable:
#include <stdio.h>
void call(int *ptr);
int main(void)
{
int a, b;
call(&a);
call(&b);
printf("%d, %d\n",a , b);
}
void call(int *ptr)
{
static int store = 0;
store += 50;
*ptr = store;
}
Program output:
50, 100
Note that you may also be able to do this as follows, without any modifications to main(). But be warned that this method invokes undefined behavior! It is undefined behavior to write to a location past the end of an array object, and in the case of a and b, these are considered to be array objects of size 1. Here we are assuming that this write will work, and that a and b are stored next to each other in memory. We further assume that a has the higher address in memory.
I would say that you should never do this, but I can see no other way to modify a from the function call() without knowing the address of a. You have been warned.
void call(int *ptr)
{
*ptr = 100;
*(ptr + 1) = 50;
}
Try something like this:
void call(int *ptr)
{
*ptr = 100;
}
int main ()
{
int a, b;
a = 50;
call(&b);
printf("%d, %d",a , b);
}
See demo
Maybe you want this:
int main ()
{
int a, b;
call(&a, &b);
printf("%d, %d",a , b);
}
void call(int *ptr1, int *ptr2)
{
*a = 50;
*b = 100;
}
To change a local variable in function a by calling function b you have two options.
1) Let function b return a value that you assign to the variable in function a. Like:
int b() {return 42;}
void a()
{
int x = b();
printf("%d\n", x);
}
This does, however, not seem to be what you are looking for.
2) Pass a pointer to the variable to function b and change the variable through that pointer
void b(int* p) // Notice the * which means the function takes a pointer
// to integer as argument
{
*p = 42; // Notice the * which means that 42 is assigned to the variable
// that p points to
}
void a()
{
int x;
b(&x); // Notice the & which means "address of x" and thereby
// becomes a pointer to the integer x
printf("%d\n", x);
}
int main()
{
int a,b;
call(&b);
printf("%d, %d\n", a,b);
}
int call(int *ptr)
{
int *m;
m = ptr++;
*ptr = 50;
*m = 100;
}
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;
}