Character Types and Arrays

Character Types and Arrays - possible to have sizeof(char)...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
Character Types and Arrays There are a couple of differences in the way that ANSI C and C++ treat character constants and arrays of characters. One of these has to do with the type of a character constant. For example: #include <stdio.h> int main() { printf("%d\n", sizeof('x')); return 0; } If this program is compiled as ANSI C, then the value printed will be sizeof(int), typically 2 on PCs and 4 on workstations. If the program is treated as C++, then the printed value will be sizeof(char), defined by the draft ANSI/ISO standard to be 1. So the type of a char constant in C is int, whereas the type in C++ is char. Note that it's
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: possible to have sizeof(char) == sizeof(int) for a given machine architecture, though not very likely. Another difference is illustrated by this example: #include &lt;stdio.h&gt; char buf[5] = &quot;abcde&quot;; int main() { printf(&quot;%s\n&quot;, buf); return 0; } This is legal C, but invalid C++. The string literal requires a trailing \0 terminator, and there is not enough room in the character array for it. This is valid C, but you access the resulting array at your own risk. Without the terminating null character, a function like printf() may not work correctly, and the program may not even terminate....
View Full Document

Ask a homework question - tutors are online