Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

Using Parentheses

Sometimes the expressions you create can be evaluated in several ways. Here's an example:

myInt = 5 + 3 * 2;

You can add 5 + 3 and then multiply the result by 2 (giving you 16). Alternatively, you can multiply 3 by 2 and add 5 to the result (giving you 11). Which is correct?

C has a set of built-in rules for resolving the order of operators. As it turns out, the * operator has a higher precedence than the + operator, so the multiplication will be performed first, yielding a result of 11.

Though it helps to understand the relative precedence of the C operators, keeping track of them all is hard. That's why the C gods gave us parentheses! Use parentheses in pairs to define the order in which you want your operators performed. The following statement


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint