Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single, double quotes and sizeof('a') in C/C++

Tags:

c++

c

gcc

I was looking at the question Single quotes vs. double quotes in C or C++. I couldn't completely understand the explanation given so I wrote a program:

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

I compiled them using both gcc and g++ and these are my outputs:

gcc:

sizeof(ch)   : 1  
sizeof('a')  : 4  
sizeof("a")  : 2  
sizeof(char) : 1  
sizeof(int)  : 4  

g++:

sizeof(ch)   : 1  
sizeof('a')  : 1  
sizeof("a")  : 2  
sizeof(char) : 1  
sizeof(int)  : 4  

The g++ output makes sense to me and I don't have any doubt regarding that. In gcc, what is the need to have sizeof('a') to be different from sizeof(char)? Is there some actual reason behind it or is it just historical?

Also in C if char and 'a' have different size, does that mean that when we write char ch = 'a';, we are doing implicit type-conversion?

like image 605
Pratt Avatar asked May 15 '12 18:05

Pratt


People also ask

Why sizeof (' a ') is 4 in C?

'a' by default is an integer and because of that you get size of int in your machine 4 bytes.

What is double quote in C?

In C and C++ the single quote is used to identify the single character, and double quotes are used for string literals. A string literal “x” is a string, it is containing character 'x' and a null terminator '\0'. So “x” is two-character array in this case. In C++ the size of the character literal is char.

Can you use double quotes for char?

A single quote is used for character, while double quotes are used for strings.

What are single quotes and double quotes?

In America, Canada, Australia and New Zealand, the general rule is that double quotes are used to denote direct speech. Single quotes are used to enclose a quote within a quote, a quote within a headline, or a title within a quote.


2 Answers

In C, character constants such as 'a' have type int, in C++ it's char.

Regarding the last question, yes,

char ch = 'a'; 

causes an implicit conversion of the int to char.

like image 152
Daniel Fischer Avatar answered Sep 27 '22 19:09

Daniel Fischer


because there is no char just intgers linked int a character

like a is 62 i guess

if you try printf("%c",62); you will see a character

like image 39
ucefkh Avatar answered Sep 27 '22 20:09

ucefkh