3

I'd like to know, how to calculate integer values of strings in single quotes ' '.

My sample code is:

#include <stdio.h>

int main()
{
    int c = 'aA';
    int d = 'Aa';

    printf( "%d %d" , c, d);

    return 0;
}

And the output is:

24897 16737

What are those numbers? Is there any formula to calculate them ?

paradigmatic
  • 40,153
  • 18
  • 88
  • 147
dumluregn
  • 43
  • 8
  • That is wrong, you have to use double quotes on strings. – imreal Nov 14 '12 at 18:15
  • @Nick Oh really? No, not at all. –  Nov 14 '12 at 18:16
  • @H2CO3 are multibyte integers considered strings? – imreal Nov 14 '12 at 18:21
  • @Nick No, they aren't. **But:** what OP has is valid, it just means something different. –  Nov 14 '12 at 18:22
  • At one time, this was closed as a duplicate of [What do single quotes do in C++ when used on multiple characters?](http://stackoverflow.com/questions/7459939/what-do-single-quotes-do-in-c-when-used-on-multiple-characters) Given that the alternative is a C++ question and this is C, it is not altogether surprising that someone objected and removed the duplicate information — but the fact that it was marked as a duplicate is still recorded. Not sure what to do best, but at least you don't have to go hunting through the edit history to find the purported duplicate. – Jonathan Leffler Jul 25 '15 at 07:03

3 Answers3

5

These are:

  1. not strings!

  2. multibyte integers, of which the value is implementation-defined, but it is usually calculated using this formula:

    integer value of 1st character multiplied by (2 << CHAR_BITS) + integer value of 2nd character

So, assuming your C locale uses ASCII and you have 8-bit bytes, 'aA' becomes

97 * 256 + 65

which is 24897.

Multicharacter literals are of type int.

2

It is the value of multi-character character stored in your variables

Durairaj Packirisamy
  • 4,635
  • 1
  • 21
  • 27
1

The value of a multi-character constant is implementation-defined.

§ 6.4.4.4 Character constants
The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined.

md5
  • 23,373
  • 3
  • 44
  • 93