title: Tricky C function testing knowledge static, global, local variables and pointers
body: <p>Disclaimer: Yes this is a homework problem. I'm having a particularly difficult time understanding what the function f2 does.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  int i = 10; /* global variable */
  int j = 1; /* global variable */
  /* Forward function declarations */
  void swap(int, int); int f1(int);
  void f2(int, int *);
  
  int main()
  {
      {
          int i = 1;
          int j = 10;
          swap(i,j); printf("i = %d j = %d\n", i,j);
          j = f1(i++); printf("i = %d j = %d\n", i,j);
          f2(f1(i),&amp;j); printf("i = %d j = %d\n", i,j);
          //which j does this refer to? The static variable, global, or local and why
      }
      j = f1(i/2); printf("i = %d j = %d\n", i,j);
      f2(f1(i),&amp;j); printf("i = %d j = %d\n", i,j);
      return 0;
  }
  void swap(int a, int b)
  {
      int temp;
      temp=b; b=a; a=temp;
  }
  int f1(int x)
  {
      static int j = 5;
      i++;
      j+=x;
      return j;
  }
  void f2(int x, int *p)
  {
      *p+=x;
      *p = (*p&gt;20) ? 20 :*p++;
  }
  </code></pre>
  
  <p>When I run this code into the compiler, I get the following answer:</p>
  
  <pre><code>i = 1 j = 10
  i = 2 j = 6
  i = 14 j = 14
  i = 13 j = 14
  i = 14 j = 20
  </code></pre>
  
  <p>I understand the first set of i and j, the reason being swap does nothing because the variables a and b are deleted in the heap. </p>
  
  <p>For the second set, we increment the i in main and then we use the value 1 as x because i++ is post-increment. We create a static variable j, the global variable x gets increased to 11, and it returns j as 6 because x is added to j. After the function is completed, the i variable in the main gets incremented to 2. This leads to 2 and 6.</p>
  
  <p>For the third print statement, I first call f1(i) which is equal to two, this resets j to 5 and increments the global variable i to 12. Then j gets set to 7 and we return 7 for f1(i). Then this is the part I am having difficulty on. We then pass the memory location of j as the parameter, but which j do we pass and why? From the output it seems as if the static j's memory is being passed but I'm not sure. </p>
  
  <p>As we go into the function f2, we get *p+=x, which I believe gives the value 14 because x is set to 7 from earlier and j is also 7. What I do not get is the second line: "*p = (*p>20) ? 20 :*p++;". What does this even mean? From the output it seems to have copied the value of j into i.</p>
  
  <p>What does the second line of code in the function f2 do and which j (the bolded one with a &amp; sign in front of it) is called in the line "f2(f1(i),&amp;<strong>j</strong>); printf("i = %d j = %d\n", i,j);".</p>