Brief Full Advanced Search Search Tips
|  |  | To access the contents, click the chapter and section titles. C++ in Plain English (Publisher: IDG Books Worldwide, Inc.) Author(s): Brian Overland ISBN: 1558284729 Publication Date: 04/01/96 Search this book:
Previous | Table of Contents | Next
These statements look a lot like initialization inside a data declaration. In fact, in C++ there is very little difference between initialization and assignment except that initialization creates a variable and assigns it a value.
| Initialization of variables is more restricted in the C language. You can use only constant values to initialize in a data declaration. In C++, this restriction is relaxed; you can use any valid expression to initialize.
#### Printing Output You can use the printf function to print simple strings or to print formatted output displaying any number of numeric values. For example, the following lines of code print two lines, each displaying the value of certain variables. Note that you must first include STDIO.H and declare each variable before using it.
    #include <stdio.h>

    void main () {
       int date = 10, d2 = 15;
       float tmp = 45.0, t2 = 33.5;

       printf(“On Dec. %d, temperature was %f. \n”, date, temp);
       printf(“On Jan. %d, temperature was %f. \n”, d2, t2);
    }
Note that %d should correspond to an integer argument and %f should correspond to a floating-point argument. These lines of code print the following results:
    On Dec. 10, temperature was 45.0000.
    On Jan. 15, temperature was 33.5000.
This example introduces another aspect of printing in C++: in a C++ string, the special character \n causes printing to start on a new line. (Not surprisingly, this character has the name newline.) The character could be omitted from the second string in this case, but if it were omitted from the first string, all the output would run together as shown next. Unlike the Basic PRINT statement, the printf function does not automatically append a newline.
    On Dec. 10, temperature was 45.0000. On Jan. 15, temperature
       was 33.5000.
The newline character is an example of a C++ escape sequence, which begins with a backslash. Other sequences include \t, which prints a tab; and \”, which prints a double-quotation mark. To print an actual backslash, by the way, use two backslashes: \\.
| With C++, but not C, you can choose to use stream operators to do input and output rather than use functions such as printf and scanf. Stream operators are at least as easy to use as printf, but I’ve put them off until Chapter 4. (By all means, skip ahead if you’re interested.) As an example, the first line of output in this section could be printed this way:
         #include <iostream.h>

         void main () {
              int date = 10, d2 = 15;
              float temp = 45.0, t2 = 33.5;

              cout << “On Dec. ” << date;
              cout << “,the temperature was ” << temp <<
                    “.\n”;
         }
#### Getting Input The scanf function is a counterpart to printf, but scanf reads data rather than writes it. Like printf, scanf recognizes format symbols (such as %d), each of which corresponds to a numeric argument. The scanf function has quirks all its own. First, all the arguments to scanf are addresses, so you must place the address operator (&) in front of your variable (unless it is a pointer; more about that in the next chapter). Second, scanf is finicky about types. A long argument must correspond to the %1d (long decimal) symbol, and a double argument must correspond to the %1f (long floating-point) symbol. The following lines of code show how you could prompt for and retrieve four different kinds of data. You cannot print a prompt string using scanf: you must use printf to print the string. Note the format symbols used here: %d, %1d, %f, and %1f.
    #include <stdio.h>

    void () {
       int i;
       long lng;
       float flt;
       double dbl;

       printf(“Enter a value for i: ”);
       scanf(“%d”, &i);

       printf(“Enter a value for lng: ”);
       scanf(“%ld”, &lng);

       printf(“Enter a value for flt: ”);
       scanf(“%f”, &flt);

       printf(“Enter a value for dbl: ”);
       scanf(“%1f”, &dbl);
    }
### Some C++ Quirks C++ has some syntactical quirks (and everything in this section applies equally to C). By “quirks” I mean features of the syntax that are not especially difficult, but that may throw you if your background is in another programming language such as Basic, FORTRAN, or Pascal. In any case, they are things to watch for. #### Watch Out for That Semi! When you’re starting to program with C or C++ for the first time, probably the most common error is to forget to type the semicolon (;). It’s also possible to type a semicolon where C++ doesn’t expect one. The rule for using semicolons is more complex than in Basic or FORTRAN (which don’t use them) but a little more consistent and straightforward than in Pascal. Terminate every statement with a semicolon unless one of the following is true: 1. The statement is actually a directive, such as #include or #define, or 2. The statement is a compound statement. In practice this means that you don’t place a semicolon after a terminating brace (}) unless it is the end of a class or variable declaration. (You’ll learn more about classes in Chapter 5, “A Touch of Class.”) The simple program shown in Figure 2.1 demonstrates the rule and the two exceptions. Figure 2.1 Using semi-colons in C ++. C++ uses a semicolon to indicate the end of a statement—rather than rely on the end of a physical line—you don’t need line-continuation characters for statements. Any time a statement threatens to grow wider than the physical screen, you can simply spread the statement across multiple lines. For example:
       printf(“On %d/ %d/ %d, the temperature was %f. \n”,
          date,
          month,
          year,
          temp);
Another consequence of C++ syntax is that you can place several statements on one line, as in the following four assignments. Remember that a semicolon terminates each statement, including the last one.
        a = 0; b = 0; c = 0; d = 0;
There is an even more compact way to do all these assignments, as I explain in the next section. #### Assignments Are Expressions, Too One of the most fundamental units of grammar in the C++ language is that of the expression. Generally speaking expressions evaluate to a value (although void expressions do not). An expression is either a variable, a constant, a function call, or a compound expression made up of smaller expressions connected by operators (such as +, -, *, /, and so on). One of the most surprising things about C and C++ is that the assignment operator (=) is an operator just like any other, and an assignment expression is an expression just like any other. This probably means nothing to you until you consider that any assignment expression can be placed inside a larger expression. This means that you can assign the same value to several variables using a single, compact statement.
    a = b = c = d = 0; // Initialize vars to 0.
To understand what this statement does, consider the rule for assignments: an assignment evaluates to the value of the left operand, after assignment (in other words, the value that was assigned). So an expression such as d = 0 first assigns 0 to d and then evaluates to 0. Associativity for assignment is right-to-left, so the rightmost assignments are evaluated first. Figure 2.2 shows how the complete statement performs each assignment, each time reusing the value 0 in the next assignment. Figure 2.2 Multiple assignments in C ++. This feature of C++ is a useful convenience, but it has a side effect that can leap up and bite you. When an assignment appears inside a conditional test, it is still an assignment even though it looks like a test for equality. The problem is that the assignment, as always, evaluates to the value assigned. For example, in the following code, the assignment i = 5 unconditionally evaluates to 5, which indicates true (all nonzero values are “true”).
    if (n = 5)                        // ERROR! n gets 5.
       printf(“n is equal to 5.\n”);  // Always executes!
Previous | Table of Contents | Next
[an error occurred while processing this directive]

| Products | Contact Us | About Us | Privacy | Ad Info | Home Use of this site is subject to certain Terms & Conditions, Copyright © 1996-2000 EarthWeb Inc. All rights reserved. Reproduction whole or in part in any form or medium without express written permission of EarthWeb is prohibited. Read EarthWeb's privacy statement.