Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to store a C data type in a variable?

Tags:

c

types

Is it possible to store a C data type in a variable?

Something like this:

void* type = (byte*);

Here is a scenario, where I wrote a test case and tried to print out a byte array using certain data types for use in printf, depending on the given parameters:

void print_byteArray(const void* expected, size_t size, 
        bool asChars, bool asWCharT) {
    int iterations;
    char* format;
    if (asChars) {
        iterations = (size / (sizeof (char)));
        format = "%c";
    } else if (asWCharT) {
        iterations = (size / (sizeof (wchar_t)));
        format = "%lc";
    } else {
        iterations = (size / (sizeof (byte)));
        format = "%x";
    }
    int i;
    for (i = 0; i < iterations; i++) {
        if (asChars) {
            printf(format, ((char*) expected)[i]);
        } else if (asWCharT) {
            printf(format, ((wchar_t*) expected)[i]);
        } else {
            printf(format, ((byte*) expected)[i]);
        }
    }
    fflush(stdout);
}

This looks like inefficient code. I'd imagine it that one could size-down the for-loop body to a single line:

printf(format, ((type) expected)[i]);
like image 504
zsawyer Avatar asked Jul 15 '13 00:07

zsawyer


1 Answers

No, there's no such type that can store a type in standard C.

gcc provides a typeof extension that may be useful. The syntax of using of this keyword looks like sizeof, but the construct acts semantically like a type name defined with typedef. See here for detail.

Some more examples of the use of typeof:

This declares y with the type of what x points to.

typeof (*x) y;

This declares y as an array of such values.

typeof (*x) y[4];

This declares y as an array of pointers to characters:

typeof (typeof (char *)[4]) y;

It is equivalent to the following traditional C declaration:

char *y[4];

To see the meaning of the declaration using typeof, and why it might be a useful way to write, rewrite it with these macros:

#define pointer(T)  typeof(T *)
#define array(T, N) typeof(T [N])

Now the declaration can be rewritten this way:

array (pointer (char), 4) y;

Thus, array (pointer (char), 4) is the type of arrays of 4 pointers to char.

like image 103
Yu Hao Avatar answered Oct 13 '22 21:10

Yu Hao