-1

simple code as:

#include<stdio.h>
int main()
{
 printf("%s", "Hello World\n");
 return 0;
}

is it possible to change output to display the variable type and the occupied X bytes in memory and the largest value it can hold?

thx in advance

  • 1
    What variable? There are no variables in your code. Please clarify your example and how it relates to your question. – kaylum Sep 07 '20 at 23:34
  • 1
    C does not provide introspection, but you can certainly do things like `printf("x is an unsigned int with size %zd\n", sizeof x);` – William Pursell Sep 07 '20 at 23:55

1 Answers1

1

C does not have any kind of reflection before C11. To print the type of a variable, you can either hardcode it into the format string:

#include <stdio.h>

int main(void) {
    int x = 0;
    printf("x is an int with a value of %d\n", x);
}

// prints "x is an int with a value of 0"

or you can use the macros in the linked answer.

To get the amount of memory a given variable occupies, you can use sizeof:

#include <stdio.h>

int main(void) {
    int x = 0;
    printf("x occupies %zu bytes in memory\n", sizeof(x));
}

// usually prints "x occupies 4 bytes in memory"
// (int's size is determined by the compiler)

There exists a limits.h header that defines several macros for the maximum and minimum values of all built-in types. However, there is no way to dynamically get the maximum value of a given type aside from incrementing a variable until it overflows.

#include <stdio.h>
#include <limits.h>

int main(void) {
    printf("int has a maximum value of %d\n", INT_MAX);
}

// usually prints "int has a maximum value of 2147483647"
// (int's maximum and minimum values are determined by the compiler)
atirit
  • 1,492
  • 5
  • 18
  • 30