c is there a way to test type of variable? or overload methods?

842 Views Asked by At

i need to pass an int or a string into a push function for a stack. normally i would just overload the function and have one that takes in a string parameter and one that takes in an int parameter so that the appropriate function would be called just based off of the parameters. i wrote the spots in comments where i would normally include the type. i just got stuck there.

void push(Stack *S, /* int or a string */ element)
{        
    /* If the stack is full, we cannot push an element into it as there is no space for it.*/        
    if(S->size == S->capacity)        
    {                
        printf("Stack is Full\n");        
    }        
    else        
    {                
        /* Push an element on the top of it and increase its size by one*/ 

        if (/* element is an int*/)
            S->elements[S->size++] = element; 
        else if (/* element is a string */)
            S->charElements[S->size++] = element;
    }        
    return;
}
5

There are 5 best solutions below

1
On

There is no function overloading in c.

You could pass the type in as an argument, make the element parameter a pointer and then re-cast the pointer to the appropriate type.

0
On

This is a situation where you could use a union and that would automatically manage things for you:

typedef union {
   int integer; 
   char* string;
} Item;

or if need type checking anyway, you could use a struct with type and union inside:

typedef enum { INTEGER, STRING } Type;

typedef struct
{
  Type type;
  union {
  int integer;
  char *string;
  } value;
} Item;
0
On

You have to use the facility provided in the language only. I do not think that there is a way to check if a variable is string or int in C. moreover element can not save both string and int be careful here . So go for function overloading. Good luck

1
On

You can try it in this way

void push (Stack *S,void *element)
    {
     (*element) //access using dereferencing of pointer by converting it to int
     element // incase of char array
    }

    //from calling enviroment
    int i =10;
    char *str="hello world"
    push(S,&i) //in case of int pass address of int
    push(S,str) // in case of char array
0
On

If you have a compiler that already implements that part of C11, you could go with the new feature _Generic. clang, e.g, already implements this and for gcc and cousins there are ways to emulate that feature: P99

It works usually through macros, something like this

#define STRING_OR_INT(X) _Generic((X), int: my_int_function, char const*: my_str_function)(X)