Search code examples
ctype-conversionsizeofimplicit-conversionstring-literals

I am a beginner in programming in c,need help in sizeof() string constant?


/**** Program to find the sizeof string literal ****/

#include<stdio.h>

int main(void)
{
printf("%d\n",sizeof("a")); 
/***The string literal here consist of a character and null character,
    so in memory the ascii values of both the characters (0 and 97) will be 
    stored respectively  which are found to be in integer datatype each 
    occupying 4 bytes. why is the compiler returning me 2 bytes instead of 8 bytes?***/

return 0;
}

Output:

2

Solution

  • The string literal "a" has the type char[2]. You can imagine it like the following definition

    char string_literal[] = { 'a', '\0' };
    

    sizeof( char[2] ) is equal to 2 because (The C standard, 6.5.3.4 The sizeof and alignof operators)

    4 When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1.

    A character constant in C indeed has the type int. So for example sizeof( 'a' ) is equal to sizeof( int ) and usually equal to 4.

    But when an object of the type char is initialized by a character constant like this

    char c = 'a';
    

    an implicit narrowing conversion is applied.