Home > database >  Is there any function or way to find datatype of a variable in C
Is there any function or way to find datatype of a variable in C

Time:12-28

#include "stdio.h"
#include "stdlib.h";

int main()
{
    char x[] = "234";
    int y;
    
    y = atoi(x);
    printf("\nCONVERTED TO INT: %d",y);
}

In the above code how can I find or check the datatype of variable y

CodePudding user response:

As commented something might work with help of c11 generic and GNU extensions in determining the data type variable.

#define IS_COMPATIBLE(x, T) _Generic((x), T:1, default: 0) It is used to determine the datatype of T by choosing the data type which match with x and replace with 1 on success otherwise default 0.

_Generic(x) is keyword acts as a switch that chooses operation based upon data type of argument passed to it.

And typeof(y) is GNU extension.

Note: Only variable modified(dynamic) types can be determined at runtime by typeof() extension.

#define IS_COMPATIBLE(x, T) _Generic((x), T:1, default: 0)
int main()
{
    char x[] = "234";
    int y;
    int int_var;
    y = atoi(x);
    if(IS_COMPATIBLE(int_var,typeof(y))){
        printf("The underlying data type of y is INT");
    }
    printf("\nCONVERTED TO INT: %d",y); 
}

CodePudding user response:

C is a quite strongly typed language. Any variable (or function parameter) that is visible has a data type defined by the near-by source code.

You have defined the variable in your source:

int y;

So y is an int.

You can find the data type of any variable by looking at its declaration or definition.

  •  Tags:  
  • c
  • Related