Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to print out the type of a variable/pointer in C?

Tags:

c

types

I want to print out (or otherwise ascertain) the type of some variable in my program. Is there a good way to do it? By good, I mean a way that works, even if it means intentionally throwing compiler errors.

For example:

client.c:55: error: incompatible types in assignment 

is the error I'm getting right now. What I WANT is it to tell me something like:

client.c:55: error: attempting to assign type struct a to type struct b 

or a function that I can use like so:

printf(gettype(x)); 

which would output:

struct b 
like image 603
Ritwik Bose Avatar asked Jan 29 '10 08:01

Ritwik Bose


People also ask

How do you print the datatype of a variable?

To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.

Can you get the type of a variable in C?

C is statically typed language. You can't declare a function which operate on type A or type B, and you can't declare variable which hold type A or type B. Every variable has an explicitly declared and unchangeable type, and you supposed to use this knowledge.

How do I print a variable address from a pointer?

To print the address of a variable, we use "%p" specifier in C programming language. There are two ways to get the address of the variable: By using "address of" (&) operator. By using pointer variable.

Can you print a variable in C?

Using printf function, we can print the value of a variable.


1 Answers

I have just discovered how to do this.

printf("%d", variable); 

If variable is not an int then gcc -Wall will complain that the types don't match - and will print out the type of the variable, which is exactly what you are looking for.

like image 81
Ariel Avatar answered Sep 19 '22 17:09

Ariel