2

Am I right in saying that the difference between 'A' and "A" in C is:

'A' - Means a character 1 byte (8 bits) long containing A.

"A" - Means a string which is 2 bytes (16 bits) long which holds an A and a NULL character.

Are my explanations correct?

Thanks.

Supertecnoboff
  • 6,406
  • 11
  • 57
  • 98
  • 1
    Yes, your explanation is correct. – unxnut May 05 '13 at 16:15
  • 4
    No, actually that's not correct. `'a'` is of type `int`, which can't be 8 bits. – Mat May 05 '13 at 16:16
  • @Mat So what exactly happens when we say `char test='a'`?Does only the least significant byte of 4-byte 'A' gets assigned to `test`? – Rüppell's Vulture May 05 '13 at 16:31
  • @Rüppell'sVulture: the usual conversion will take place (at least in theory), and it's lossless in this case given what I quoted in comments to your answer - the value is guaranteed to be representable as a char. – Mat May 05 '13 at 16:42

2 Answers2

2

You are absolutely correct.But you got to bear in mind that when you use those as rvalues they are different.One has the type char, and can be used as an int as it is implicitly converted to the ASCII value, while the other has type char*.

Let me illustrate my point with a code if that helps:

 int num='A';  //Valid, assigns 65 to num
 char test=65;  //Valid, as test will be 'A' after this
 char *ptr="A"  //Valid, assigns  address of string "A" to pointer ptr
 printf("%c,%d",'A','A'); // Output will be   A,65
 printf("%p",(void*)"A"); //Will print address where string "A" is
 printf("%c","A"); ///WRONG
 printf("%s","A"); //Works

Edit For the finer nuances, if you feel your understanding is up to that mark yet,refer to Mat's comment.Else read it after a few weeks when you have advanced further in your study of C.

Rüppell's Vulture
  • 3,583
  • 7
  • 35
  • 49
  • 3
    `'a'` does **not** have type `char` in C. – Mat May 05 '13 at 16:18
  • @Mat Let me rephrase it properly.I am trying to say something but dont' have the rigorous words for it.You suggest it so that I can edit my answer for the OP. – Rüppell's Vulture May 05 '13 at 16:18
  • @Mat I want to say something like `char is basically dressed up int`..... – Rüppell's Vulture May 05 '13 at 16:19
  • 2
    There's no dressing up. If you see `'a'` in C source code, it's type is `int`. It's called an "integer character constant". The value of that: "If an integer character constant contains a single character or escape sequence, its value is the one that results when an object with type char whose value is that of the single character or escape sequence is converted to type int." (§6.4.4.4/10 ~C11 draft) – Mat May 05 '13 at 16:24
2

Basically yes. The main nuance is byte vs. char. Where you say byte, you should say char. On most systems a char is one byte. There are a few that use larger objects to store a char.

DrC
  • 7,528
  • 1
  • 22
  • 37