Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: sizeof() related doubts?

Tags:

c

sizeof

#include <stdio.h>
#include <string.h>

main()
{    
   printf("%d \n ",sizeof(' '));
   printf("%d ",sizeof(""));
}

output:

4
1

Why o/p is coming 4 for 1st printf and moreover if i am giving it as '' it is showing error as error: empty character constant but for double quote blank i.e. without any space is fine no error?

like image 436
shivi Avatar asked Jul 17 '14 12:07

shivi


3 Answers

The ' ' is example of integer character constant, which has type int (it's not converted, it has such type). Second is "" character literal, which contains only one character i.e. null character and since sizeof(char) is guaranteed to be 1, the size of whole array is 1 as well.

like image 187
Grzegorz Szpetkowski Avatar answered Sep 25 '22 12:09

Grzegorz Szpetkowski


' ' is converted to an integer character constant(hence 4 bytes on your machine), "" is empty character array, which is still 1 byte('\0') terminated.

like image 29
Aniket Inge Avatar answered Sep 26 '22 12:09

Aniket Inge


Here in below check the difference

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

   }

here a is defined as character whose data type size is 1 byte.

But 'b' is character constant. A character constant is an integer,The value of a character constant is the numeric value of the character in the machine's character set. sizeof char constant is nothing but int which is 4 byte

this is string literals "a" ---> array character whose size is number of character + \0 (NULL). Here its 2

like image 37
vinay hunachyal Avatar answered Sep 23 '22 12:09

vinay hunachyal