Statements and Expressions - PowerPoint PPT Presentation

1 / 24
About This Presentation
Title:

Statements and Expressions

Description:

We will use variable names that are meaningful (except for occasional counters ... For example we will not use both bankBal and totalBalance as variable names. ... – PowerPoint PPT presentation

Number of Views:63
Avg rating:3.0/5.0
Slides: 25
Provided by: donaldl1
Category:

less

Transcript and Presenter's Notes

Title: Statements and Expressions


1
Statements and Expressions
2
Statements
  • the statement is the basic unit for building C
    programs
  • most statements are imperative (i.e., tell the
    computer to do something)
  • statements end with a semicolon, not with the end
    of a line (important point!)
  • Example statements
  • cout ltlt "Hello" //statement that does
    output
  • totPay hourlyRate numHours 10.0
    //assignment stmt

3
Lines vs Statements
  • the compiler ignores whitespace (i.e., spaces,
    tabs, line feeds, carriage returns)
  • preprocessor directives should be on one line
  • can not break strings between two lines
  • C allows us to write the body of our function
    main (i.e., our program) as
  • cout ltlt "\nHello World" ltlt endl return 0
  • but this would be difficult to read

4
Expressions
  • An expression is a grouping of variables,
    constants and operators that specifies a
    computation
  • An expression results in a value
  • Examples amount 5
  • (temp -2) rate
  • An expression is not a statement
  • statements end in a semicolon
  • a statement tells the computer to do something
  • a statement may include several expressions

5
C Variables
  • A variable is the name of a location in computer
    memory
  • All variables need to be declared
  • C is a "strongly typed" language (i.e., when a
    variable is declared, the built-in data type or
    the class of an object at which the variable will
    point must be explicitly identified)
  • declaration vs definition
  • declaration lets the system know you will use a
    name and specifies type
  • a definition also reserves space
  • int studentCount // this is a definition space
    is reserved
  • Declaring a variable that will point at an object
    implicitly instantiates it (unlike Java or
    Smalltalk)
  • Car firstCar

6
Identifiers
  • names given to program elements are referred to
    as identifiers
  • these names all have similar rules for their
    construction
  • use lower case and upper case letters, digits and
    underscore
  • can not start with a digit
  • any length, but generally ignore beyond 250
  • can not use a keyword (e.g., if, while, return)

7
Popular Conventions for Variable Naming
  • Lots of different conventions exist -- choice
    may be influenced by a vendor or package, or be
    set by company, project or individual
  • Consistent adherence to convention improves
    readability and understandability
  • C code is often (usually?) written with
    inconsistent styles
  • Popular C variable naming conventions
  • all lower case (payrate)
  • mixture of upper and lower case (PayRate)
  • lots of underscores for readability (Pay_Rate)
  • Java style (payRate)

8
Our Convention for Variable Names
  • We will apply the following conventions (similar
    to what we did for Java)
  • We will use letters and numbers
  • We will not use special characters including
    spaces, dots, underlines, pound signs, etc.
  • The first letter will be lower case
  • We will use variable names that are meaningful
    (except for occasional counters that we might
    call i, j, x, etc.)
  • We will concatentate words, and capitalize each
    after the first, e.g., bankBal, thisAcctNum,
    totAmt
  • If we abbreviate, we will be consistent. For
    example we will not use both bankBal and
    totalBalance as variable names.

9
Our Convention for Struct and Class Names
  • In creating names of structs and classes we will
    apply the same rules as for variable names,
    except the first character will be upper case
  • Example
  • an object's name myCar (or thisOldWreck)
  • the struct or class name Car
  • Another Example aPerson and Person

10
Classes(A Review)
  • A class refers to the model, template or master
    form for a category or type of object
  • Classes might be Person, Employee, BankAccount,
    Car, TextWindow and MyProgram
  • We need to differentiate these from instances of
    the classes, such as person1, anEmployee, myCar
    and person2
  • Don't forget instance is another word for
    object
  • You create an instance of a class (i.e., an
    object) with a constructor, which may be either
    implicitly or explicitly called
  • Person thisPerson // declares thisPerson
    which now refers to a Person object has made an
    implicit call to constructor
  • ptrPerson new Person() //the new operator
    requests an amount of memory from the OS, and
    returns a pointer of the appropriate type to that
    memory (note very DIFFERENT than in Java or
    Smalltalk)

11
C Statements
  • Some are assignment statements
  • structure varName expression // l-value
    r-value
  • examples balance 0.
  • newAmt (myCar.getWt()) 200
  • fullName lastName
  • Some are not assignment statements

12
C Statements
  • Some statements are not assignment statements
  • structure expression
  • function(arguments)
  • object.method(arguments)
  • CarcarCount() //calling a static ftn
  • examples cout ltlt "Amount " ltlt amt
  • myCar.setWt(2400)
  • strcpy (sameName, origName)
  • duration(time1)

13
When do you use an assignment statement?
  • You use an assignment statement when you need to
    capture or retain the value or object created by
    evaluating a C expression
  • no capture myCar.getWt()
  • capture currentWeight myCar.getWt()
  • Other cases can be more complicated
  • may depend on what statements or functions are
    available
  • a function can change values of variables used as
    parameters
  • sometimes either is possible
  • Sometimes the choice can be complicated. Rely
    on
  • analysis
  • experience

14
When Do You Need to Preserve a Value or Object?
  • If you will need to refer to it later, such as
    for the following purposes
  • to use in a calculation
  • if it is an object, to send it a message
  • to print it out
  • to send it to another routine (i.e., to use as an
    argument for a function)

15
C Expressions Using Objects
  • A variable is a reference to a location in memory
    where a data type, a struct or an object (i.e.,
    an instance of a class) is stored
  • Objects can receive messages
  • a variable myCar.getWeight()
  • class CreditCardnextID()
  • a data type no! No! NO!!!!
  • What is the role of the object, the member
    function (e.g., method) and the argument or
    arguments?

16
What can an expression return?
  • What is returned or created as a result of
    executing each of the following C expressions
  • myCar.getWeight()
  • inputWindow.prompt("Enter Name ")
  • 4 (15.8 - 12.3/7.)
  • myCar.setWeight(3000)
  • inputStreamObject.readDouble()
  • myFile.locatePerson("Jones")

17
Not All Expressions Return a Result
  • Which expressions do not return a result
  • xxx myCar.getWeight()
  • xxx inputWindow.prompt("Enter Name ")
  • xxx 4 (15.8 - 12.3/7.)
  • xxx myCar.setWeight(3000)
  • xxx inputStreamObject.readDouble()
  • xxx myFile.locatePerson("Jones")
  • Do you use an assignment statement where the
    expression does not return a result?

18
Declaring variable types to match the result of
an expression
  • What type of variable (e.g., int, string, Person,
    etc.) would we need for each assignment
    statement?
  • xxx myCar.getWeight()
  • xxx inputWindow.prompt("Enter Name ")
  • xxx 4 (15.8 - 12.3/7.)
  • xxx myCar.setWeight(3000)
  • xxx inputStreamObject.readDouble()
  • xxx myFile.locatePerson("Jones")

19
Arguments
  • An argument can be a
  • Literal data type (e.g., 5, -43.7, 'z')
  • Variable containing a data type (custBal)
  • Literal objects and arrays (e.g., "Sally Wynn")
  • Variable name containing an object (thisCar)
  • An expression (e.g., toupper(middleInitial),
    (custBal 15.6)/2.3)

20
Learning More C
  • To learn more C
  • Create a separate, small program with minimal
    code to test a new feature
  • Use printed and on-line sources (see syllabus)
  • text
  • reference books
  • C on-line help system
  • on-line tutorials, etc. (see syllabus)
  • check "Resources" discussion list

21
Looking at Values During Execution
  • When your program is not producing correct
    results, you need to examine what your program is
    actually doing
  • You can
  • Trace the logic by hand (always a good first
    step)
  • Look at the values of variables and the internal
    content of objects during execution. You can
  • print out values
  • use Integrated Development Environment's debug
    features

22
MS Visual C 6.0 Debug Features
  • We will learn how to
  • Set breakpoints
  • Do step by step execution
  • Watch values
  • Trace values at termination

23
Some Key Points (Slide 1)
  • A variable is a name of a location in memory
    where a data type, struct or object may be stored
  • C is "strongly typed" which means that you have
    to declare what each variable can store
  • Follow the rules and our agreed-upon conventions
    for creating C variable names, structs and
    class names
  • C works with data types, structs and objects,
    and they are different
  • When you evaluate a C expression, the result
    can be a data type, a struct, an object, or
    nothing at all

24
Some Key Points (Slide 2)
  • You need to know what is kind of value/object is
    produced by the evaluation of a C expression
    (so you can do something with it, or assign it to
    a variable)
  • C comes with an extensive library, with many
    specialized libraries available too
  • C expressions and statements are easy to write,
    after some practice
  • Remember that is the assignment operator and
    not an algebraic equal sign
Write a Comment
User Comments (0)
About PowerShow.com