You are here:

C/Advanced pointers

Advertisement


Question
In the following code: There is a part I dont understand. "n++;" increases once only but why? why does this "while ((*f)(n))" condition increases it only once. That "while ((*f)(n))" confuses me. I do not see any end point inside the loop...

#include <stdio.h>
#include <string.h>

int f1(int (*f)(int)) {
  int n = 0;
  while ((*f)(n)) {
     n++;
  }
  return n;
}
int f2(int x) {
  return x * x + x - 2;
}
int main(void) {
  printf("%d", f1(f2));
  return 0;
}

Answer
Hi Ali,

In the code sample you provided, the function f2 is called twice. The first time f2 is called, 0 is passed to the function f2(0) = -2. The while loop iterates once and f2 is called again. On the second call to f2, 1 is passed as a parameter. (1 * 1) + ( 1 -2 ) == (1 - 1) == 0. The while loop condition is false and the program exits.

n = 0;
f2(0) = -2
n++;
f2(1) = 0  

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Tony Nazzal

Expertise

I will answer any c language programming and syntax questions.

Experience

I have almost a decade of c programming experience.

Education/Credentials
I have a bachelor of science degree and several years of industry experience.

©2016 About.com. All rights reserved.