-1

When I try to run this code, it gives the following output:

c
99
25448
4636795

I want to know how the compiler generates the last two output?

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    char ch='c';

    printf("%c\n",ch);
    printf("%d\n",ch);
    printf("%d\n",'ch');
    printf("%d","ch");

    return 0;
}
M.M
  • 138,810
  • 21
  • 208
  • 365

2 Answers2

6
printf("%c",ch);       - print normal character
printf("%d\n",ch);     - print ascii value of character
printf("%d\n",'ch');   - multi-character literal
printf("%d","ch");     - print value of pointer to string "ch"

Regarding 'ch'

25448 is 0x6368 and 63 is hex for 'c' and 68 is hex for 'h'

sujithvm
  • 2,351
  • 3
  • 15
  • 16
  • what is wchar_t wide character? – user3755129 Jun 19 '14 at 06:05
  • No, `'ch'` is a multibyte character constant, **not** wchar_t – phuclv Jun 19 '14 at 06:07
  • @LưuVĩnhPhúc can you explain the output of last two lines sir. I am new to programming – user3755129 Jun 19 '14 at 06:09
  • +1 / Just quoting the Standard showing 'ch' will be passed as `int` in C++, so the `%d` format's definitely appropriate "An ordinary character literal that contains more than one c-char is a *multicharacter literal*. A multicharacter literal, or an ordinary character literal containing a single c-char not representable in the execution character set, is conditionally-supported, has type `int`, and has an implementation-defined value.". Cheers – Tony Delroy Jun 19 '14 at 06:19
1
printf("%c", ch);     // print ch as a character
printf("%d\n", ch);   // print the ASCII value of ch
printf("%d\n", 'ch'); // print the value of the multi-character literal 'ch'
                      // implementation defined, but in this case 'ch' == 'c' << 8 | 'h'
printf("%d", "ch");   // print the address of the string literal "ch"
                      // undefined behavior, read below

About multi-character literal read here

Your code invokes undefined behavior in the last printf, since you're using the wrong format specifier. printf is expecting an integer and you're passing an address. In 64-bit system this is most probably a 64-bit value while int is 32 bits. The correct version should be

printf("%p", (void*)"ch");

Another problem is that you didn't use anything in iostream, why include it? Don't include both iostream and stdio.h. Prefer iostream in C++ because it's safer. If needed, use cstdio instead of stdio.h

And you shouldn't tag both C and C++. They're different languages

phuclv
  • 37,963
  • 15
  • 156
  • 475