0
char s[10]="welcome";

Here for example &s is of type char(*)[2]. Is there anyway in C to find the type of a variable like this?

6
  • What do you mean by "find the type"? Have you tried cdecl.org? Commented May 31, 2013 at 0:00
  • If we try to print a variable with some other format specifier in c, it gives warning as the variable is of type "char *" but you are trying to print as "int" without cast. Likewise is there any proper way to find the variable type? Commented May 31, 2013 at 0:16
  • 7
    @Patashu: No, arrays are not "more or less pointers". I suggest you read section 6. of the comp.lang.c FAQ. Commented May 31, 2013 at 0:20
  • 2
    That particular declaration is invalid, because s isn't long enough to hold the string "welcome". Commented May 31, 2013 at 0:22
  • @Keith Thompson Interesting! Thank you :D Commented May 31, 2013 at 0:24

2 Answers 2

1

Most* compilers support the typeof operator, which can be quite handy. It is essentially equivalent to C++'s decltype, so you'd probably need a macro to turn it into something useful, like a string:

#define _STRINGIFY(arg) #arg
#define STRINGIFY(arg) _STRINGIFY(arg)

*: most compilers being clang, GCC, and I believe MSVC.

Sign up to request clarification or add additional context in comments.

Comments

0

The compiler knows but that information is discarded when the compilation is complete. You cannot somehow ask at runtime for the textual description of what type of variable it is. There is no method that will return the string "char(*)[2]"

To do this, you would have to either integrate with a C compiler or write a C compiler and run your code through it at runtime.

2 Comments

This is technically correct, barring extensions such as typeof.
@RichardJ.RossIII your answer is better - I'll probably delete mine in a few minutes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.