Zeno of Elea
Zeno of Elea

Reputation: 185

Is it possible without the use of a third party library to tell how many bytes an integer type is in C at runtime

I am looking to probe at runtime the number of bytes an int is at runtime without using more than POSIX C.

Basically my thought is looking for a way to check the systems limits for UINT_MAX without having my binary rely at that information at compile time. I first thought to try sysconf() but that variable was not specified as one that can be used.

edit 1: To clarify what I am doing is building my own od program bases on reading POSIX 1003.1-2017 specifications for the od utility.

Specifically from my reading and interpretation of these lines in the extended description.

The default number of bytes transformed by output type specifiers d, f, o, u, and x corresponds to the various C-language types as follows. If the c99 compiler is present on the system, these specifiers shall correspond to the sizes used by default in that compiler. Otherwise, these sizes may vary among systems that conform to POSIX.1-2017. For the type specifier characters d, o, u, and x, the default number of bytes shall correspond to the size of the underlying implementation's basic integer type

I read that to mean the default value is based on the environment of the running system not the compiler

edit 2: sizeof was what I was looking for upon reflection I realized that my original thought would not make sense for a statically linked binary in an environment without a libc.

Thanks all.

Upvotes: 0

Views: 110

Answers (2)

izac89
izac89

Reputation: 3930

If you still want to achive it in run time you can use the following-

unsigned char myIntegerSizeOf(void) {
    int a[] = { ~0, 0 } ;
    unsigned char *a_ptr = (unsigned char *)&a[0] ;
    unsigned char count = 0 ;

    while (*a_ptr == 0xFF) { 
        count++ ; 
        a_ptr++ ;
    }

    return count;
}

count contains the answer.

Upvotes: 0

tornado
tornado

Reputation: 70

If you want to know the size of an int your executable uses, then you can use sizeof as the size does not change after beeing compiled (even if you run it on another processor).

If you want to know the size of an int your program would have if it was compiled on this machine, then the easiest way is probably compiling and running something like this:

int main() {
    printf("%zu\n", sizeof(int));
}

(Or you could grep the include directory on the running machine for UINT_MAX)

If you want to move around int's between different architectures then that's a whole different story.

If that didn't answer it please clarify your intent.

edit:

grep /usr/include/limits.h -e 'UINT_MAX' --color

works pretty well.

Upvotes: 3

Related Questions