Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to declare a function argument that can accept any type in C

2 Answers

0 votes
#include <stdio.h>
 
void AcceptAnyType(void *x, char type) {
    switch (type) {
        case 'i':
            printf("int: %d\n", *(int*)x);
            break;
        case 'c':
            printf("char: %c\n", *(char*)x);
            break;            
        case 'f':
            printf("float: %f\n", *(float*)x);
            break;
        case 's':
            printf("string: %s\n", (char*)x);
            break;
        default:
            printf("Unknown type\n");
    }
}
 
int main() {
    int i = 35681;
    char c = 'a';
    float f = 3.14f;
    char *str = "ABCD";
 
    AcceptAnyType(&i, 'i');
    AcceptAnyType(&c, 'c');
    AcceptAnyType(&f, 'f');
    AcceptAnyType(str, 's');
}
 
 
 
/*
run:
 
int: 35681
char: a
float: 3.140000
string: ABCD
 
*/

 



answered Jul 31, 2025 by avibootz
edited Jul 31, 2025 by avibootz
0 votes
#include <stdio.h>

typedef enum {
    TYPE_INT,
    TYPE_CHAR,
    TYPE_FLOAT,
    TYPE_STRING
} ValueType;

typedef union {
    int i;
    char c;
    float f;
    char *s;
} Variable;

void AcceptAnyType(Variable v, ValueType t) {
    switch (t) {
        case TYPE_INT:
            printf("int: %d\n", v.i);
            break;
        case TYPE_CHAR:
            printf("char: %c\n", v.c);
            break;
        case TYPE_FLOAT:
            printf("float: %f\n", v.f);
            break;
        case TYPE_STRING:
            printf("string: %s\n", v.s);
            break;
        default:
            printf("Unknown type\n");
    }
}

int main() {
    Variable var;

    var.i = 35681;
    AcceptAnyType(var, TYPE_INT);

    var.c = 'a';
    AcceptAnyType(var, TYPE_CHAR);

    var.f = 3.14f;
    AcceptAnyType(var, TYPE_FLOAT);

    var.s = "ABCD";
    AcceptAnyType(var, TYPE_STRING);

    return 0;
}



/*
run:

int: 35681
char: a
float: 3.140000
string: ABCD

*/

 



answered Jul 31, 2025 by avibootz
...