I have a very simple question.
in this piece of code when will the value of n be decremented?
#include<stdio.h>
void func(int n)
{
//text//
}
int main()
{
int n=10;
func(n--);
return 0;
}
now when func() is called is the value of n decremented when control comes back to main() or is it decremented at that time only but n=10 is passed to func().
Please explain, also if there is a way to check the value then that will be really helpful.
When a function is called, all it's arguments are evaluated (in an implementation-defined order) before the function can start - it's a sequence point. So, after all the arguments are evaluated the function can finally begin.
What this means is that n-- is evaluated and yields the value 10 for the function. At the moment the function has begun n is already 9 but the n parameter of the function hold the value 10.
A simple way to check this:
void func(int n, int *np)
{
printf("Outside: %d\n", *np);
}
int main(void)
{
/* ... */
func(n--, &n);
}
The decrement will happen before the call to func, however func will be passed a copy of the old value still.
Consider the following modification to your program which illustrates this:
#include <stdio.h>
static int n;
void func(int m)
{
printf("%d,%d\n", n, m);
}
int main()
{
n = 10;
func(n--);
return 0;
}
Prints:
9,10
I think your question is better expressed by this code:
#include <stdio.h>
static int global_n;
void func(int n)
{
printf("n = %d, global_n = %d\n",
n, global_n);
}
int main()
{
global_n = 10;
func(global_n--);
return 0;
}
This demonstrates that the function is passed the old value, but the decrement happens before the call.
n = 10, global_n = 9
Related
I am a beginner in programming. I referred to power function in chapter 1 and modified it to be power_sum function. My calculation is to insert value of bits in "show_val()" to show range of each variable. The problem is in the main when I want to insert a value into show_val. Please guide me how to solve this. Thank you.
#include <stdio.h>
int power_sum(int base, int n);
void show_val(int power);
int main() {
unsigned char vc = show_val(8);
/* I try to show range of unsigned char here, but because show_val
is a void function, so it becomes error.*/
}
/* power_sum: raise base to n-th power and sum up; n => 0 */
int power_sum(int base, int n) {
int i, p, sum;
p = 1;
sum = 0;
for (i = 1; i <= n; ++i) {
p = p * base;
sum = sum + p;
}
sum = sum - 2;
return sum;
}
/* show_val: to show value of each variable */
void show_val(int pw) {
int n;
int i;
n = power_sum(2, pw);
for (i = 0; i < 10; ++i) /* to display increments of a value ten times */ {
printf("%d\n", ++n);
}
}
You are trying to assign void function void show_val(int pw) (a function that returns nothing) to unsigned char vc variable. If you want to return value from show_val function change: int show_val(int pw) and return something.
Otherwise, if you don't want to return anything, you can just call function in main:
int main()
{
show_val(8);
}
unsigned char vc = show_val(8);
Let us break the above piece of code into LHS and RHS.
LHS :
Its a variable expecting a character to be inputed.
Now what is being done in RHS
RHS:
You have given show_val(8)
Which is a mistake
Why?
Because if you see you show_val declaration:
void show_val(int)
You are returning a void i.e nothing.
And trying to equate with char on LHS.
So, the compiler will definitely throw an error.
There are more changes to be made,
1st edit this part correctly in the question if you are clear and then we can look upon the other changes.
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;
}
What does parameter do in programming ?
For example
void main()
int n = 6;
int test(int n)
Is the int n inside the int test refer to the void main int 6 ?
Can anyone explain further for me.
Tq guys have better understanding now.
Based on your description..
n = 6 both in the main function and the test function.
E.g.
void main()
{
int n = 6;
test(n); //shows 8
print("%d", n); //shows 6
}
int test(int n)
{
n = n + 2;
return n;
}
Here we have two 'n' in two functions representing two different values.
If that function is inside main then "int test(int n)" is declaration of function and u need to write that function outside main.When u call test function u just pass value and no declaration of variable is required.For example test(n) will refer the n in the main program.
Below is my code:
When I run it, I get the following statements:
X is equal to 1 and k is equal to 1
X is equal to 0 and k is equal to 0
What I wish to achieve is to have both statements stating the same thing (equal to 1). I understand I can just set the integers x, and k respectively to 1 underneath the if statement, however I want to know how to store a value after the function is executed, so that x and k remain equal to one after execution of the second function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void run_times( int runs);
int main (){
int i;
while ( i <3) {
run_times(i);
printf("Looped\n");
i++;
}
}
void run_times( int runs) {
int *x,k;
if (runs == 0) {
x = &k;
*x = 1;
printf("X is equal to %d and k is equal to%d\n", *x, k);
}
if (runs == 1){
printf("X is equal to %d and k is equal to%d\n", *x, k);
}
Thanks in advance
void run_times( int runs) {
static int *x,k;
A static variable means that variable keeps its values between invocations.
Note that the code as asked is running with uninitialized local variables, which is undefined behavior. So it may or may not work anyway, IDE one runs as you want it to without any changes! http://ideone.com/X7dqHr
Note that we do not have that problem with static variables as they are initialized to zero. See: Why are global and static variables initialized to their default values?
You can achieve that by making k static (there is really no need for the pointer in this case). The result will be similar to global variable - which are generally a bad idea. Usually it makes more sense to make the declaration local:
void run_times(int *x, int runs) {
printf("x is equal to %d\n", *x);
if (runs == 0) {
*x = 1;
}
}
This way it will still work, if you ever decide you need two separate states:
int main() {
int k0 = 0;
int k1 = 2;
int i = 0;
while ( i <3) {
run_times(&k0, i);
run_times(&k1, i);
i++;
}
}
It should be also clearer to the reader, as you are not passing data via hidden variables.
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;
}