08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 2 ■ C – The Basics

The value of a string constant is the sequence of characters without the beginning and ending

quotes. Thus, the value of "Are you OK?" is Are you OK?.

If you want the double quote to be part of a string, you must write it using the escape

sequence \", as in

"\"Don't move!\", he commanded"

The value of this string is

"Don't move!", he commanded

Each \" is replaced by " and the beginning and ending quotes are dropped.

The C language does not have a predefined string type. This presents difficulties for the

beginning programmer since he cannot work with string variables the way he can with numeric

variables.

In C, a string is stored in an “array of characters.” Since we discuss characters in Chapter 6

and arrays in Chapter 8, we could be patient and wait until then to understand what an array

is, how strings are stored, and how we can use them to store a name, for instance. Or, we could

accept a few things on faith and reap the benefit of being able to work with strings, in a limited

way, much sooner than we normally would. We’ll be impatient and choose the latter.

Suppose we wish to store a person’s name in some variable name. We can declare name as

follows:

char name[50];

This declares name to be a “character array” of size 50. As we will explain in Chapter 8, this

allows us to store a maximum of 49 characters in name. If you find this is too much (or too little) for

your purposes, you can use a different number.

If we want to, we can assign a string constant to name in the declaration, thus:

char name[50] = "Alice Wonder";

This stores the characters from A to r, including the space, in name. The quotes are not stored.

Once this is done, we could print the value of name using the specification %s in printf, thus:

printf("Hello, %s\n", name);

This will print

Hello, Alice Wonder

The value of name replaces %s.

Unfortunately, we cannot assign a string constant to name, other than in the declaration of

name. C does not permit us to write an assignment statement such as

name = "Alice in Wonderland"; // this is not valid

39

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!