I've googled this and it looks to me like what I am trying to do is impossible. I'm trying to write a Display function that can take different parameters and call the appropriate function based on those parameters (i.e. function overloading). I've read that C doesn't allow this, but I figured I'd post the code and see if anyone has anyone has any ideas. It compiles fine in C++. It compiles fine in C if I change it so no two functions have the same names (i,e. change the names to DisplayInt and DisplayIntArray ). Is that simply what I must do or is there a way to make it so the two functions have the same name?

#include <stdio.h>
#include <stdlib.h>

void Display (int* arr, int size);
void Display (int number);



int main ()
{
   int* c;
   int d;
   int i;
   int a[5];
   int* b = (int*) malloc (5 * sizeof (int));


   // initialize single integer and pointer
   d = 6;
   c = &d;

   // initialize arrays
   for (i = 0; i < 5; i++)
   {
      a[i] = 0x10 * i + 0xF;
      b[i] = 0x10 * i + 0xB;
   }

   Display (a[2]);
   printf ("\n");
   Display (b[2]);
   printf ("\n");
   Display (d);
   printf ("\n");
   Display (*c);
   printf ("\n");
   Display (a,5);
   printf ("\n");
   Display (b,5);
   printf ("\n");

   free (b);

   getchar ();
   return 0;
}


// display an array of integers
void Display (int* arr, int size)
{
   int i;
   for (i = 0; i < size; i++)
   {
      Display (*(arr+i));
      if (i < size - 1)
         printf (", ");
   }
}

// display a single integer
void Display (int number)
{
   printf ("%08x", number);
}

Is that simply what I must do or is there a way to make it so the two functions have the same name?

There is a way, but it means writing a dispatch function or macro and all of the complexity involved. It is pretty simple if you are working with a small number of known functions, but something generic will probably be hairy. It is easier and probably better overall to avoid all of those moving parts and just use different names for each function. ;)

If you want to see how other language's handle function overloading, try Googling "name mangling" and you'll see the compiler just renames or mangles the said functions names according to some scheme based on the parameter types...

There is a way, but it means writing a dispatch function or macro and all of the complexity involved. It is pretty simple if you are working with a small number of known functions, but something generic will probably be hairy. It is easier and probably better overall to avoid all of those moving parts and just use different names for each function. ;)

Yeah, that sounds like a bit more than I want to tackle. I'll just give them different names. Thanks to both of you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.