Why is my C integer printing as a non-printable character?

  • Thread starter Thread starter jd12345
  • Start date Start date
  • Tags Tags
    Integer
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 2K views
jd12345
Messages
251
Reaction score
2
Ok so I was trying something in C when i found something i don't understand:-
code is:-
int c = 1;
printf("%c\n",c);
(not writing the include and return 0 stuff)

so when i run this it gives an output of a 2x2 box like this:-
0 0
0 1

whats happening. When i put the 1 in commas like this int c= '1' then it gives an ouput 1. Thats good but when i don't put the comma it gives this box, why?
 
Physics news on Phys.org
jd12345 said:
Ok so I was trying something in C when i found something i don't understand:-
code is:-
int c = 1;
printf("%c\n",c);
(not writing the include and return 0 stuff)

so when i run this it gives an output of a 2x2 box like this:-
0 0
0 1

whats happening. When i put the 1 in commas like this int c= '1' then it gives an ouput 1. Thats good but when i don't put the comma it gives this box, why?

I don't understand what you're talking about with the 2x2 box...

In C a character is a number: specifically, the value of a character is its ASCII code. Some characters, such as those whose ASCII codes are in the range 0 - 31, are nonprinting control characters.

There is a difference between the number 1 and the numeric character '1'. The value of the first is 1, of course, but the value of '1' is 49.

You can convince yourself of this by running this code.
Code:
printf("%c\n", 1);  // You won't see anything on the screen.
printf("%d\n", '1'); // Should print 49.

BTW, this-- , -- is a comma. This -- ' -- is a single quote.
 
oh sorry about the single quote and comma error

printf("%c\n",1); prints the box.
I tried it - on linux (ubuntu) with GCC (if that matters)
 
The 'box' you are seeing is what happens when you print one of the non-printable ASCII chars.

int c = 1; // assign a new int the value 1
int c = '1'; // assign a new int the integer value of the character '1' (which is 49)

printf("%c", c); // print the character representation of the integer variable c
printf("%d", c); // print the integer representation of the integer variable c

Have a look at the ASCII table. Notice that the integer 1 represents the SOH (start of heading) character which is not printable. If you want to print the number one as stored in your integer variable, you should use the %d format specifier not %c.