Click here to Skip to main content
15,882,163 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hey guys, can someone please explain what this function is doing? Especially the last part.


C#
int fu2(int *a, int b);
int main()
{
  	int x = 38953;
	int arr[]={4,-5,2,-3,4,-4,6};
	
	printf("%d\n",fu2(arr,7));
	return 0;
}
int fu2(int *a, int b)
{
    int c=*a;
    if(b>1)
        c=fu2(a+1,b-1);
    return (*a<0 ? (*a>c ? *a :(c<0?c:*a)) : (c<0?c:0));
}
Posted
Updated 5-Feb-13 4:19am
v2

1 solution

It looks something like a bubble sort perhaps a custom one. Fairly horrible code that is seriously lacking comments and may well have been written by someone trying to be clever. That happens enough.
Two things to note:
fu2 is recursive, i.e. it's a function that calls itself.
The tertiary operator ? works like this.
x ? y : z; means
if( x )
{ 
  y; 
}
else
{
  z;
}


so fu2 can be rewritten as
int fu2(int *a, int b)
{
    int c=*a;
    if( b > 1 )//end condition, stop recursing when b reaches 1
    {
        c = fu2( a + 1, b - 1 );//recursive call to fu2 function 
    }
    
    if( *a < 0 )
    {
       if( *a > c )
       {
         return *a;
       }
       else
       {
          if( c < 0 )
          {
             return c;
          }
          else
          {
             return a;
          } 
       }
    }
    else
    {
       if( c < 0 ? )
       {
         return c;
       }
       else
       {
         return 0;
       }
    }
}


Now you can follow what it's doing, plug in the numbers and step through it in the dugger to see what happens. Keep a watch on the contents of the array but having done the expansion it doesn't look like it gets alterred so this is some sort of search possibly for the smallest negative number.
Let us know when you've cracked it.
 
Share this answer
 
Comments
idobry 5-Feb-13 10:57am    
Thx man really good explanation!
Abhishek Pant 5-Feb-13 11:10am    
never forgot to vote that when you find a good solution. as it help others when they search here.By the way, good explanation! +5
Albert Holguin 5-Feb-13 11:41am    
+5
Abhinav S 5-Feb-13 12:35pm    
5+

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900