Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How the number of byte required for string representation is calculated

I am not sure how LEN(LONG_MAX) prints 19, it should be 8 only.

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

#define STRING(x) #x
#define LEN(x) ((int)sizeof(STRING(x)) - (int)1)

int main()
{
    printf("%d\n",LEN(LONG_MAX));
    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It seems in the used by you system sizeof( long ) is equal to 8.

In this case the value of LONG_MAX is 9223372036854775807. That is the number contains 19 digits.

Due to this macro

#define STRING(x) #x

the value is converted to the string literal "9223372036854775807".

String literals are stored as character arrays with trailing terminating zero character '\0'. So sizeof( "9223372036854775807" ) is equal to 20 (19 plus one for the terminating zero character '\0' of the string literal).

As a result the whole expression produced by this macro

#define LEN(x) ((int)sizeof(STRING(x)) - (int)1)

is equal to 19.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading