Title: Basic Syntax
1Basic Syntax
- Variables, Types, and Operators
2What is a Variable?
3- A variable is a place to store a piece of
information. Just as you might store a friend's
phone number in your own memory, you can store
this information in a computer's memory.
Variables are your way of accessing your
computer's memory. - Of course, your memory changes over time. Your
friend moves across country and has a new phone
number, and your friend's new phone number will
replace the old one in your memory. Over time, as
you acquire new friends, your memory will keep
changing to store different pieces of
information. Likewise, a computer's memory can
change over time, if you tell it to. Since
variables are your access point to your
computer's memory, it makes sense that you'd be
able to change the information in a computer's
memory otherwise, they wouldn't be called
variables (they'd be called statics).
4- Why should you care about variables? Variables
are the essence of any computer program! Without
variables, computers would be useless. Imagine a
program which asks the user for two numbers and
adds them together, and prints the result. - AddTwoNumbers
- Enter the first number 2
- Enter the second number 5
- The sum of 2 and 5 is 7.
-
5- Sounds simple, right? But let's do a little
role-playing to see what the computer has to do
to execute this program. Instead of this
interaction between a person and a computer,
let's imagine the same kind of conversation
between two people, Sol and Frank. - Sol Hey Frank, I just learned how to add two
numbers together.Frank Cool!Sol Give me the
first number.Frank 2.Sol Ok, and give me the
second number.Frank 5.Sol Ok, here's the
answer 2 5 7.Frank Sheesh! This guy is
unbelievable!
6- After Frank says "2", Sol has to store that
number in his memory somewhere. It may be stored
in short-term memory, but he has to store it
somewhere before Frank gives him the second
number. Even if Frank were to give him two
numbers in the same sentence, Sol would have to
store the numbers somewhere in his memory to add
them together. - In the sample program described above, the
computer would most likely store "2" in a
variable, then store "5" in a variable, and then
calculate the sum by calculating the sum of the
numbers store in the two variables.
7- Although there are similarities between a
person's memory and a computer's memory, there
are some pretty big differences. In C, you need
to grab a little piece of the computer's memory
before you can use it. In other words, you have
to tell the computer that you're planning to
store a number in a variable before you can
actually do it. This is called declaring a
variable. To declare a variable, you need to know
what kind of information it will store (i.e.,
will it store a number, or a text-string, or
something else) and how you plan to refer to the
variable (i.e., the variable's name).
8C imposes fairly strict rules on how you can
name your variables
- variable names must begin with a letter
- variable names are "case-sensitive" (i.e., the
variable "myNumber" is different from the
variable "MYNUMBER" which is different from the
variable "mYnUmBeR") - variable names can't have spaces
- variable names can't have special characters
(typographic symbols)
9- What can you name your variables? In general,
variable names can be composed of letters,
numbers, and underscores (_) - . However, C reserves certain keywords which
have special meaning to the language, and you are
not allowed to use any of these keywords as
variables names. Some examples of C keywords
are - int, for, else, and class.
- You can, however, use keywords in the middle of a
variable name, such as "foreign" or "classical".
For a complete list of C keywords, view the
appendix.
10Variable Types and Declaring Variables
11Variable Types
- A variable type is a description of the kind of
information a variable will store. Programming
languages vary regarding how strict they require
you to be when declaring a variable's type. Some
languages, like Perl, do not require you to
announce the type of a variable. Other languages
require you to declare some variables as numbers
and others as text-strings, for example. C, a
strongly-typed language, requires you to be even
more specific than that. Instead of declaring a
variable as a number, you must say whether it
will store integers or decimals. In C, the type
of an integer is int and the type of a decimal is
float (floating-point number).
12Declaring Variables
- Declaring a variable in C is simple. Let's say
you want to declare a variable of type int called
myAge. That is to say, the variable myAge will
store an integer. In C, this is written - int myAge
- All this does is tell the computer that you plan
to use an integer, and that the integer's name is
myAge.
13- In some languages, variables are initialized to 0
- that is, a variable's initial value will be 0.
This is not true of C! Sometimes your variables
will be initialized to 0, but sometimes they will
be initialized with garbage. As you might
anticipate, this can cause some nasty bugs. Let's
take a look at another sample program.
14- include ltiostream.hgt
- int main()
-
- int myAge
- cout ltlt "My age is " ltlt myAge ltlt endl
- return 0
-
- You might expect the program to output "My age is
0". In fact, the output of this program is
unreliable. On one system you may get output of
"My age is 11" another system may output "My age
is 0" yet another system may output "My age is
3145". That's what it means to have a variable
initialized with garbage.
15- It is always a good idea to initialize your
variables with some value. If you don't know what
a variable's initial value should be, initialize
it to 0. Initializing a variable is easy. Let's
fix the above program so that it always outputs
"My age is 22". The first line of the main
function initializes myAge by assigning it a
value immediately. - include ltiostream.hgt
- int main()
-
- int myAge 22
- cout ltlt "My age is " ltlt myAge ltlt endl
- return 0
-
- That's all there is to it! By the way, the equals
sign ("") is called an operator and will be
covered later in Section 3.
16Casting of Variables
17How Do Computers Store Variables?
- In any programming language, and especially in
C, it's important to have at least a cursory
understanding of what the computer is doing
"behind the scenes". Since we're talking about
variables in this chapter, it's important to
understand how a computer stores the information
in variables.
18More Variable Types
- For reasons not explained here, variables can
only store finite numbers. Suppose that the size
of a particular data type, that we'll call a
gorb, is 1 byte. That means that gorbs can only
represent 281 28 256 distinct values. So,
gorbs might be able to store only the numbers
between 0 and 255 (inclusive). Any number that
you tried to store in a gorb which was smaller
than 0, or larger than 255, would not be stored
correctly it would be stored as one of the
values between 0 and 255. However, maybe you want
to be able to store positive and negative numbers
in gorbs, in which case you'd only be able to
store 128 negative numbers and 128 positive
numbers. Since we need to be able to store 0
also, you might decide that the range of values
for a gorb is -128 to 127.
19- We've already learned about two different data
types (not including "gorbs"!) int and float.
What are the sizes of these data types, and what
are the limits on the kinds of values that they
can store? We just saw that a data type whose
size is 1 byte can store 256 distinct values.
Data types of size 2 bytes can store 282 216
65536 different values. Using the same formula,
we determine that data types of size 4 bytes can
store 284 232 4,294,967,296.
20Unfortunately, the size of data types like int
and float are not standard across all systems.
The size of an int depends on your operating
system and your hardware. Here are some typical
values for ints and floats, along with some other
important data types.
type typical size description
short 2 2 bytes stores a short (i.e., small) integer
int 4 bytes stores an integer
long 4 bytes stores a long (i.e., large) integer
float 4 bytes stores a floating-point number
double 8 bytes stores a "double-precision" floating-point number
21When to Cast
- Casting a variable is a complicated name for a
simple concept. When you cast a variable from one
type to another, all you are doing is telling the
computer to use a different type to store the
variable. Why would you need (or want) to do
this? Let's say you declared a variable of type
short. In most cases, that would mean that the
largest positive value you could store would be
32,767. But somewhere in your program, you
realize that you're going to have to do a
calculation which could increase the value over
this maximum. Perhaps you are computing very
large Pythagorean triplets.
22- To calculate the value of c (the hypotenuse), you
need to take the square root of the quantity a2
b2. But what if a or b is very large? Then
squaring that number will make it much, much
larger -- and if the value becomes bigger than
32,767 your values will not be what you expected
(if you had used a short to store a or b.
Remember, a short can only store the values
between -32,768 and 32,767, so if you try to
store a number out of this range, your data will
be incorrect!
23- So, the solution is to cast. We can cast the
numbers to a larger data type, such as an int or
a long, for the purposes of the calculation --
and then we can cast them back to a short when we
are done, since the final value for c will
probably be small enough to be stored in a short.
24- This is a somewhat trivial example, since in this
case you could store the numbers in ints or longs
from the beginning and not worry about it! A more
useful example might be if you have a number
which represents an average. You'll probably want
to represent the number with a floating-point
type like a float or a double so that it is
accurate while you are computing it (otherwise
you'd only be able to store a value like "26"
instead of "26.3141885"). Let's say that you want
to display the value in a table, yet the table
would look cluttered if you displayed
"26.3141885", so you decide to simply display the
integer portion, 26. You can cast the float to an
int and then display the int in the table --
since ints can't store floating-point numbers,
the decimal portion of "26.3141885" will be
truncated and you will be left with "26".
25How to Cast
- Casting in C is easy. Let's say that you have a
float storing a number like "26.3141885", and you
want to have an int storing the integer portion
instead. Here's how to do it
26- int GetAverage()
-
- // assume that regularAverage and specialAverage
store two floats - Float_total_Average regularAverage
specialAverage - // cast totalAverage to an int
- Int_truncated_Average (int) totalAverage
- // return the truncated value
- return truncatedAverage
-
- There's a little bit of syntax that you haven't
seen before, but the key part to notice is the
line of code that reads int truncatedAverage
(int) totalAverage. What we're doing here is
taking a float, totalAverage, which stores some
kind of decimal number (like 82.41832), and
getting rid of the ".41832" part by casting it to
an int. That works because the int is only
capable of storing integers, so it simply stores
the integer portion of totalAverage.
27Operators
- Booleans True and False
- Boolean operators in C
- Arithmetic operators in C
- Equality operators in C
- Assignment operators in C
28Booleans True and False
- Before talking about operators, we'll take a
quick aside into booleans, since we'll need to
know what a boolean is before discussing
operators. A boolean value is one that can be
either true or false. No other values are
allowed. Booleans and boolean operations are at
the heart of programming. Many times in a
program, you'll want to do one thing if a certain
condition is true, and a different thing if the
condition is false. For example, when processing
a series of checkboxes, you may want to take an
action only if a box is checked, and do nothing
otherwise. That's when you'll want to use a
boolean.
29- Most programming languages have a type for
booleans, usually called "boolean" or "bool".
Some C compilers recognize the type bool,
others do not. For now, assume that your compiler
supports the bool type. We'll discuss what to do
if your compiler doesn't, in a moment. - In order to use boolean logic to your advantage,
you need to learn about the three basic boolean
operations. They are called and, or, and not.
Each operation takes either one or two boolean
inputs, and returns a boolean output. They are
often represented by symbols known as "gates",
shown below.
30 and The "and" operation takes two inputs and produces one output. If both inputs are true, the output is true in all other cases, the output is false. It can be interpreted as follows "I will return true if input 1 and input 2 are true."
or The "or" operation takes two inputs and produces one output. If either of the inputs are true, the output is true otherwise (i.e., if neither input is true), the output is false. It can be interpreted as follows "I will return true if either input 1 or input 2 is true."
not The "not" operation takes one input and produces one output. If the input is true, the output is false. If the input is false, the output is true. In other words, the "not" operation takes the input and returns its opposite.
31Boolean operators in C
- There are operators in C which behave just as
the boolean gates shown above! We'll show you an
example of how to use each one.
32and
- The "and" operator is used by placing the "and"
symbol, , in between two boolean values. - //suppose that Fran is tired
- bool franIsTired true
- //but Fran doesn't have to wake up early
- bool franMustWakeUpEarly false
- //will Fran go to sleep now?
- bool bedTime franIsTired franMustWakeUpEarly
33- What does this chunk of code do? It initializes
two variables, franIsTired and franMustWakeUpEarly
, to true and false, respectively. Then, in the
third line of code (not including comments!), we
determine that Fran will go to sleep if and only
if the "and" operation is true -- that is, if
both inputs to the "and" operation are true. In
this case, the first input is true and the second
input is false. Since "and" requires both inputs
to be true in order for the output to be true,
but one of the inputs is false, the output will
be false. So, the variable bedTime will store the
value false.
34or
- The "or" operator is used by placing the "or"
symbol, , in between two boolean values. - //suppose that Graham is tired
- bool grahamIsTired true
- //but Graham doesn't have to wake up early
- bool grahamMustWakeUpEarly false
- //will Graham go to sleep now?
- bool bedTime grahamIsTired
grahamMustWakeUpEarly
35- This example is very similar to the example
involving Fran, except notice the key difference
whether or not Graham goes to sleep is determined
differently. Graham will go to sleep if he is
tired or if he needs to wake up early. Whereas
Fran would go to sleep only if both conditions
were true, Graham will go to sleep if either
condition (or both) is true. Therefore, the value
of bedTime is true.
36not !
- The "not" operator is used by placing the "not"
symbol, !, before a boolean value. - //suppose that Julian stayed up late
- bool julianStayedUpLate true
- //will Julian be peppy tomorrow?
- bool julianIsPeppy !julianStayedUpLate
37- This example illustrates the "not" operator. At
the end of this block of code, the variable
julianIsPeppy will take on the opposite value of
julianStayedUpLate. If julianStayedUpLate were
false, then julianIsPeppy would be true. In this
case, the opposite is true, so julianIsPeppy gets
a value of false.
38- It is perfectly legal in C to use boolean
operators on variables which are not booleans. In
C, "0" is false and any non-zero value is true.
Let's look at a contrived example. - int hours 4
- int minutes 21
- int seconds 0
- bool timeIsTrue hours minutes seconds
- Since hours evaluates to true, and since minutes
evaluates to true, and since seconds evaluates to
false, the entire expression hours minutes
seconds evaluates to false.
39Arithmetic operators in C
Arithmetic operators Arithmetic operators Arithmetic operators
name symbol sample usage
addition int sum 4 7
subtraction - float difference 18.55 - 14.21
multiplication float product 5 3.5
division / int quotient 14 / 3
modulo ("mod") int remainder 10 6
40- They all probably look familiar with the
exception of mod (). The mod is simply the
remainder produced by dividing two integers. In
the example shown in the table above, if we treat
10 / 6 as an integer divison, the quotient is 1
(rather than 1.666) and the remainder is 4.
Hence, the variable remainder will get the value
4.
41Equality operators in C
- You are undoubtedly familiar with equality
operators, even if you don't know it. An equality
operator is one that tests a condition such as
"is less than", "is greater than", and "is equal
to". You will find it useful to be able to
compare two numbers using expressions like "x is
less than y". - Let's say you are writing software for a bank ATM
(automated teller machine). A customer makes a
request for a certain amount of cash, and your
responsibility is to determine if they should be
allowed to withdraw that amount. You could decide
to use the following algorithm "if the amount
requested is less than the account balance, that
amount should be withdrawn otherwise, the
customer should be notified and no money should
be withdrawn." Makes sense, right? So, the next
step is coming up with some pseudo-code. Once you
have pseudo-code, writing the C code will be
easy.
42Pseudo-code for the ATM problem might look like
this
- if the amount requested lt account balance then
- withdraw the amount requested
- otherwise
- withdraw nothing and notify the customer
43Now that we have pseudo-code, writing the C
code is as simple as "translating" your
pseudo-code into C. In this case, it's easy
- if (amountRequested lt accountBalance)
-
- withdraw(amountRequested)
-
- else
- withdraw(0)
- notifyCustomer()
-
44- You'll notice some new syntax in this example,
but don't worry about it too much. Pay close
attention to the very first line, which checks to
make sure that the amount requested is less than
the account balance. The way it works is, if the
expression between parentheses (()) evaluates to
true, then the first block of code will be read.
That is, the code inside the first set of curly
braces () will be executed. If the expression
in parentheses evaluates to false, on the other
hand, then the second block of code (the code
following the word else) will be read. In this
case, the first block of code withdraws the
amount requested by the customer, while the
second block of code withdraws nothing, and
notifies the customer.
45- That wasn't so hard! All we did was take the
original English description of how we would
solve the problem, write some pseudo-code for the
English description, and translate the
pseudo-code into C. - Once you know how to use one equality operator,
you know how to use all of them. They all work
the same way they take the expressions on either
side of them, and either return true or false.
Here they are
46Equality operators Equality operators Equality operators Equality operators
name symbol sample usage result
is less than lt bool result (4 lt 7) true
is greater than gt bool result (3.1 gt 3.1) false
is equal to bool result (11 8) false
is less than or equal to lt bool result (41.1 lt 42) true
is greater than or equal to gt bool result (41.1 gt 42) false
is not equal to ! bool result (12 ! 12) false
47Assignment operators in C
- Believe it or not, you've already been using
assignment operators! Probably the most common
assignment operator is the equals sign (). It is
called "assignment" because you are "assigning" a
variable to a value. This operator takes the
expression on its right-hand-side and places it
into the variable on its left-hand-side. So, when
you write x 5, the operator takes the
expression on the right, 5, and stores it in the
variable on the left, x. - Remember how the equality operators, like lt and
!, returned a value that indicated the result?
In that case, the return value was either true or
false. In fact, almost every expression in C
returns something! You don't always have to use
the return value, though -- it's completely up to
you. In the case of the assignment operators, the
return value is simply the value that it stored
in the variable on the left-hand-side.
48- Sometimes your code will use the return value to
do something useful. In the ATM example, one line
of code was executed if the condition was true
(that is, if the equality operator returned
true). Two different lines were executed if the
condition was false. - Other times, you'll completely ignore the return
value, because you're not interested in it. Take
a look at the following code
49- int x
- int y
- x 5
- y 9
- cout ltlt "The value of x is " ltlt x ltlt endl
- cout ltlt "The value of y is " ltlt y ltlt endl
- int sum
- sum x y
- cout ltlt "The sum of x and y is " ltlt sum ltlt endl
50- This chunk of code shows why you might want to
throw away the return value of an operator. Look
at the third line, x 5. We're using the
assignment operator here to place the value 5 in
the variable x. Since the expression x 5
returns a value, and we're not using it, then you
could say we are ignoring the return value.
However, note that a few of lines down, we are
very interested in the return value of an
operator. The addition operator in the expression
x y returns the sum of its left-hand-side and
right-hand-side. That's how we are able to assign
a value to sum. You can think of it as sum (x
y), since that's what it's really doing. Operator
precedence is covered on the next page.
51- The other assignment operators are all based on
the equals sign, so make sure you understand that
before going on. Here's another assignment
operator . How does it work? You might guess
that it has something to do with addition, and
something to do with assignment. You'd be
absolutely right! The operator takes the
variable on its left-hand-side and adds the
expression on its right-hand-side. Whenever you
see a statement that looks like the following
52- myVar something
- it is identical to saying the following
- myVar myVar something
- That's exactly what it's doing! It's simply a
shortcut. - The other common assignment operators are -, ,
/, and . They all function just like the
operator, except instead of adding the value on
the right-hand-side, they subtract, or multiply,
or divide, or "mod" it.
53- Just as the simple assignment operator returns
the value that it stored, all of the assignment
operators return the value stored in the variable
on the left-hand-side. Here's an example of how
you might take advantage of this return value.
It's not used terribly often, but it can
sometimes be useful. - //these four variables represent the sides of a
rectangle - int left int top
- int right
- int bottom
- //make it a square whose sides are 4
- left top right bottom 4
54- All this code does is store the value in each of
the four variables left, top, right, and bottom.
How does it work? It starts on the far right-hand
side. It sees bottom 4. So it places the value
4 in the variable bottom, and returns the value
it stored in bottom (which is 4). Since bottom
4 evaluates to 4, the variable right will also
get the value 4, which means top will also get 4,
which means left will also get 4. Phew! Of
course, this code could have just as easily been
written
55- //these four variables represent the sides of a
rectangle - int left
- int top
- int right
- int bottom
- //make it a square whose sides are 4
- left 4
- top 4
- right 4
- bottom 4
- and it would have done the exact same thing. The
first way is more compact, and you're more likely
to see it written the first way. But both ways
are equally correct, so use whichever you prefer.
56Operator Precedence
57So far, we've seen a number of different
operators. Here's a summary of the operators
we've covered so far
Boolean operators , , !
Arithmetic operators , -, , /,
Equality operators lt, gt, , lt, gt, !
Assignment operators , , -, , /,
58What is operator precedence?
- Operator precedence refers to the order in which
operators get used. An operator with high
precedence will get used before an operator with
lower precedence. Here's an example - int result 4 5 6 2
- What will be the value of result? The answer
depends on the precedence of the operators. In
C, the multiplication operator () has higher
precedence than the addition operator (). What
that means is, the multiplication 5 6 will take
place before either of the additions, so your
expression will resolve to 4 30 2 , so result
will store the value 36.
59- Since C doesn't really care about whitespace,
the same thing would be true if you had written - int result 45 62
- The result would still be 36.
- Maybe you wanted to take the sum 4 5 and
multiply it by the sum 6 2 for a result of 72?
Just as in math class, add parentheses. You can
write - int result (4 5) (6 2)
60Operator precedence in C
- Operator precedence in C is incredibly easy!
Don't let anyone tell you otherwise! Here's the
trick if you don't know the order of precedence,
or you're not sure, add parentheses! Don't even
bother looking it up. We can guarantee that it
will be faster for you to add parentheses than to
look it up in this tutorial or in a C book.
Adding parentheses has another obvious benefit -
it makes your code much easier to read. Chances
are, if you are uncertain about the order of
precedence, anyone reading your code will have
the same uncertainty.
61- That having been said, here's the order of
operator precedence. In general, the order is
what you would think it is - that is, you can
safely say - int x 4 3
- and it will correctly add 4 and 3 before
assigning to x. Our advice is to read this table
once and then never refer to it again.
62(No Transcript)