The logic behind sizeof () for symbolic constants and function names

In C, the following code:

#include<stdio.h>
int main()
{
   char c='a';
   printf("%d %d",sizeof(c),sizeof('a'));
   return 0;
}

gives the result 1and 4? Explain the logic?

In addition, why sizeof(main())leads to 4, but sizeof(main)leads to 1:

#include<stdio.h>

int main()
{

   printf("%d %d\n",sizeof(main), sizeof(main()));
   return 0;
}

And in C ++, why does it sizeof('a')lead to 1, and sizeof ('av') leads to 4?

+4
source share
2 answers

Character constants in C are of type int, although this is not the case in C ++. From the draft C99 standard, the 6.4.4.4Character Constants section in paragraph 10 says (emphasis added):

int. , , , . , (, 'b') [...]

++ 2.14.3 1 ( ):

[...] , c- char, , char, [...] , c- char, . , c- char, , , int , .

, av int.

sizeof(main) , , , C99 6.5.3.4 sizeof operator 1 :

sizeof , , [...]

++ , gcc clang -pedantic :

: 'sizeof' [-pedantic]

sizeof(main()), sizeof , , , int . , :

long double func()
{
    return 1.0 ;
}

sizeof(func()) 16.

sizeof(int) 4, .

2

sizeof size_t, printf %zu.

+8

int not char s. , 'a' 4 , c, 1, char.

, int .

+4

All Articles