Click here to Skip to main content
12,451,703 members (60,231 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: C
Hey guys, can someone please explain what this function is doing? Especially the last part.


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 5-Feb-13 4:18am
idobry431
Updated 5-Feb-13 4:19am
v2

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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.
  Permalink  
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Mobile
Web02 | 2.8.160826.1 | Last Updated 5 Feb 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100