Link to home
Start Free TrialLog in
Avatar of eugene007
eugene007

asked on

smallest

A function called smallest that takes two integer pointer arguments and returns a reference to the smallest of the two?.


Can anyone please explain to me the question above?. Do I do something like bellow:


int smallest(int *a,int *b)
{

}


int main()
{
    int a,b;
    smallest(&a,&b);
}


Regards
Eugene
ASKER CERTIFIED SOLUTION
Avatar of kishorebv
kishorebv

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Kent Olsen
This sounds like homework, but it's so trivial that it's hard to answer without doing it for you.  I'll explain the correct way and you can "back up" into the required function.


Within C programming, you won't usually find a function like smallest() that deals with explicit variable types.  It can make it too tough or inefficient to deal with variable of different types.  The usual method is to write the function as a macro and let the compiler deal with casting issues.  This, too has its drawbacks, but they are generally less numerous and less common than the casting problems of a specific function.

#define Smallest(a,b) ((a) < (b) ? a : b)

will select the smallest (smaller) of the two parameters, regardless of their basic type.

Smallest ('i', 'w') will evaluate chars and return 'i'.  Smallest (146232,12345678) will evaluate ints and return 146232.  Smallest (1.4, 6.2) will evaluate floats and return 1.4.


Armed with this knowledge, you should be able to complete your smallest() function,
Kent
Avatar of klopex
klopex

This sounds an awful lot like a homework assignment... is it?
Avatar of eugene007

ASKER

well its actually a practise question found on the internet.
main purpose, lecturers are paid so little, that they hardly
are willing to work longer hours to train their students about
the basic fundamentals of programming. What I am doing now
is seeking for explanation, not copying. If I were to copy I
wont gain anything but 0. I prefer to learn thru examples
and practicals rather than being a 100% bookworm.
u r an expert, is it difficult to teach.
How do u train your junior programmers.
do u just tell them, do yourself and expect the
company to get large tenders.
> How do u train your junior programmers.

First, I insist upon them writing standard English.  For anything significant, they do designs before coding and therefore must be able to write clearly.

Second, I (or another senior engineer) will review their code, at least when they first start out.

In Massachusetts, it's not that difficult getting college hires who are competant at the basics of programming.

Gary
well atleast u review their work, in our case they dont care at all.
correct me if I am wrong, we cannot return a reference right. We can only return a pointer or a number.
modification:

int* smallest(int *a,int *b)
{
      return *a<*b?a:b;
}

int main()
{
     int a,b, *c;
     c = smallest(&a,&b);
     printf("%d",*c);
}
#include <stdio.h>

int* smallest(int *a,int *b)
{
  return *a<*b?a:b;
}

int main()
{
  int a,b, *c;
  printf("Please Enter Value 1\n");
  scanf("%d",&a);
  printf("Please Enter Value 2\n");
  scanf("%d",&b);
  c = smallest(&a,&b);
  printf("%d\n",*c);
}

This is a pretty bizarre way to implement smallest().  If you're going to code it as a function instead of a macro, pass parameters by value, not by address.  That way the compiler will recast compatible types for you.

int smallest (int a, int b)
{
  return (a < b ? a : b);
}


The code above will work in the following program:

main ()
{
  int    IValue;
  char CValue;
  int    Minimum;

  CValue = GetRandomNumber ();
  IValue = GetRandomNumber ();

  Minimum = smallest (CValue, IValue);
}


However, the function that you posted will not work since you pass pointers to integers.  When main() calls smallest(), it will place two pointers on the stack.  One to IValue, and one to CValue.  smallest() will compare the two INTEGERS at *a and *b.  Since *a is a 1-byte value this is not at all what you want.

Of course, the compiler may flag this as illegal depending on the error level that you've selected.  But some compilers (or compile options) will build you an object based on the fact that a pointer to an int is the same size as a pointer to a char.  The compiler will have no trouble producing code that will build a valid stack object.  But the program won't work because smallest() will have no way to know that *a is only one byte long.


Kent
I am using ANSI C compiler. Will it produce an error.
But the error would only accure if smallest returns a NULL right.
and also that error can be solved with:

if(c){printf("ok");}
else {printf("error");}

A error at run time would be in the form of a potentially invalid answer, not an abort.  These kinds of errors can be brutal to track down.

Many compilers today "waste" a few bytes when necessary to align data on "word" boundaries to make fetches and stores more efficient.  Just for example, lets assume that somewhere in the program are two integer variables, IntA and IntB.  Left unto itself, the compiler is likely to define these two variables at consective locations so let's assume that they are at addresses 00000004 and 00000008.  (These are unlikely to be the real addresses, but they will demonstrate the principals involved here.)  Let's also put a char at 0000000C.

Address      Value                 Name
00000004  0x05 00 00 01    IntA
00000008  0x07 00 00 00    IntB
0000000C  0x04                   CharC

Any form of smallest() that's been presented in this forum will work if the variables being compared are IntA and IntB.  (Note that which value is smallest is a function of the hardware architecture.  On a little-endian system, IntA is larger while on a big-endian system intB is larger.)

However, the variants of smallest() that pass addresses will yield very funny results if CharC is one of the arguments.  The reason being that you just don't know what's in the next three bytes.  If they are zero and you're on a little-endian machine (like Intel and AMD desktop systems) then smallest (&CharC, &IntB) will correctly return 04, the value of CharC.  If those three bytes are non-zero, then 07 (IntB) will be returned -- clearly not what you'd intended!!!!


Kent
#define smallest(a,b) ((a) < (b) ? a : b)

If I were to use this, how can I do so?.
what are the steps involve. Correct me if
I am wrong, this would actually cause smallest
to return an integer value instead of a pointer.
Thus the program wont crush.
#include <stdio.h>
#define smallest(a,b) ((a) < (b) ? a : b)

int main()
{
  int a,b, *c;
  printf("Please Enter Value 1\n");
  scanf("%d",&a);
  printf("Please Enter Value 2\n");
  scanf("%d",&b);
  c = smallest(&a,&b);
  printf("The reference for the smallest of two is %d\n",*c);
}

For a long time, this was the preferred method.  There can be problems with this, too but it should suffice for most applications.  In the sample program that I gave above (reposted here) this macro will do fine.


#define smallest(a,b) ((a) < (b) ? a : b)

main ()
{
 int    IValue;
 char CValue;
 int    Minimum;

 CValue = GetRandomNumber ();
 IValue = GetRandomNumber ();

 Minimum = smallest (CValue, IValue);
}

Note that the parameters need not be Variables.  

Minimum = smallest (IValue, 24);

FloatMin = smallest (FloatValue, 3.14159);


Kent
what if I do this:

#include <stdio.h>

int* smallest(int *a,int *b)
{
    return *a<*b?a:b;
}

void main()
{
    int a,b, *c;
    printf("Please Enter Value 1\n");
    scanf("%d",&a);
    printf("Please Enter Value 2\n");
    scanf("%d",&b);
    c = smallest(&a,&b);
    printf("The reference for the smallest of two is %d\n",*c);
}


I replace int main() to void main()

You could do that.  But why would you want to return the address of an integer?  The address of a structure (if you were interrogating fields of a structure) I could see, but returning the address of an integer has pretty limited value.

Legal?  Yes.  Will it work in this situation?  Yes.  But why would you want to?


Kent
because "return a reference to the smallest of 2".

The original question is badly phrased and ambiguous.  In C, parameters are normally refered to as passed by value or passed by reference (address).  Returned values are normally refered to as " the returned value" or "the returned address".

While "return a reference to the smallest of the two" can be interpretted as asking for the address, I don't believe that most seasoned programmers would interpret the question that way when the parameters being passed are integers.

Mostly because returning the address of an integer instead of the value doesn't really accomplish anything.  Most programs won't care WHICH integer is smaller byt they'll often want to know the smaller value.  Strings, structs, and unions are a different matter.  These are objects that are referenced by address because they have no intrinsic value unto themselves.  The fields inside a struct have value, and the characters within a string have value, but these are not atomically referencable objects.


If GaryFx, Sunnycoder, or any of the other regulars would like to add thier interpretation of the question, I'm certainly interested in hearing it.

Kent
Because the word "reference" has a specific meaning in C++, it should be avoided in talking about C code.  C has pass by value and pass by pointer, but doesn't have the C++ concept of pass by reference.  Old timers sometimes use "pass by reference" synonomously with "pass by pointer", but in spite of being technically correct, it's just too confusing to be used anymore.  In this case, "return a reference" just doesn't make sense.

What's the URL for the practice problem?  I'd be glad to gripe to the author.  Or perhaps the question is intended for C++, but the base noter only has C available.

Gary
Ill clarify this question n get back to u earliest by this everning my time.