- Forward


The C Programming Language
An Introduction for Programmers


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Identifiers
Back SMYC Forward
  • First Character:
    • Must be a letter or underscore
  • Subsequent Characters:
    • Can be a letter, digit, or underscore
  • Conventions:
    • Do not use an underscore as the first character
    • Limit identifiers to 31 characters
Comments
Back SMYC Forward
  • Line Based:
    • Any text between a // and the end of the line is a comment
  • Block:
    • Any text between a /* and a */ is a comment
Basic Data Types
Back SMYC Forward
  • Some Types:
    • char
    • double
    • float
    • int
    • long
    • short
  • An Important Point:
    • The sizes are machine-dependent
Variables
Back SMYC Forward
  • A Restriction:
    • Must be declared before they are used
  • Loose Syntax of Declarations: Click here for information.
    • type identifier [= value] [,identifier [= value]]...;
  • Examples:
    • float cost = 0.0; int lower, upper, step;
Assignment Operator
Back SMYC Forward
  • Assignment:
    • Placing a value into the memory identified by a variable/constant
  • Syntax: Click here for information.
    • variable = literal|expression ;
  • Examples:
    • height = 14.0; step = 1;
Type Conversions
Back SMYC Forward
  • The General Rule:
    • The only automatic conversions are those that convert a "narrower" operand into a "wider" one without loss of information
  • Ignoring Unsigned Operands:
    • If either operand is long double convert the other to long double
    • Otherwise, if either operand is double convert the other to double
    • Otherwise, if either operand is float convert the other to float
    • Otherwise, if either operand is long convert the other to long
  • Coercion Using the Cast Operator:
    • (type) expression
Arithmetic Operators
Back SMYC Forward
  • Basics:
    • Addition (+)
    • Subtraction (-)
    • Multiplication (*)
    • Division (/)
  • Integer Operators:
    • Integer Division (/)
    • Modulo (%)
  • Others:
    • Increment (++) and Decrement (--)
    • Negation (-)
Relational Operators
Back SMYC Forward
  • Comparison:
    • Greater than: >
    • Less than: <
    • Greater than or equal to: >=
    • Less than or equal to: <=
  • Sameness:
    • Equal to: ==
    • Not equal to: !=
Logical Operators
Back SMYC Forward
  • Binary:
    • Logical AND: &&
    • Logical OR: ||
  • Unary
    • Logical NOT: !
Bitwise Operators
Back SMYC Forward
  • Binary:
    • Bitwise AND: &
    • Bitwise OR: |
    • Bitwise XOR: ^
    • Left Shift: <<
    • Right Shift: >>
  • Unary
    • One's Complement: ~
The if Statement
Back SMYC Forward
  • Syntax: Click here for information.
    • if (boolean_expression) statement [else statement]
  • Examples:
    • if (score < 60) grade = 'F'; if (bmi >= 30.0) status = 'O'; else if (bmi >= 25.0) status = 'H';
while Loops
Back SMYC Forward
  • Syntax: Click here for information.
    • while (boolean) statement
  • Example:
    • while (width <= 10) { area = height * width; width += 1; }
do-while Loops
Back SMYC Forward
  • Syntax: Click here for information.
    • do statement while (boolean);
  • Example:
    • do { area = height * width; width += 1; } while (width <= 10);
for Loops
Back SMYC Forward
  • Syntax: Click here for information.
    • for (initialization; boolean; update) statement
  • Example:
    • for (i=0; i<size; i++) { area = i * i; }
Symbolic Names/Constants
Back SMYC Forward
  • A Note About Development:
    • Source files are preprocessed before they are compiled
  • Defining Symbolic Names/Constants
    • #define name replacement text
Enumerations
Back SMYC Forward
  • Defined:
    • A list of (normally 0-based) integer constant values
  • Syntax:
    • enum identifier {value0[=initial][, valuei]... };
  • Example:
    • enum choices {NO, YES}; enum{JAN=1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC};
Pointers
Back SMYC Forward
  • Declaration:
    • type *identifier
  • Void Pointers:
    • Most pointers point to a particular kind of entity
    • void pointers can hold any type of pointer
  • Operators:
    • Unary Dereference: *
    • Unary Address Of: &
Arrays
Back SMYC Forward
  • Defined:
    • An array is a fixed-size, ordered collection of homogeneous values
  • Declaration:
    • type identifier [ size ]
  • Individual Elements:
    • identifier [ index ]
  • A Note:
    • Arrays are 0-based
Strings
Back SMYC Forward
  • The Key Point:
    • C does not have a string type, instead it uses arrays of characters
  • The Idiom:
    • So that the length of the array can be determined, all "strings" have a '\0' character as their last element
  • "String" Literals:
    • For convenience, "string" literals do not include the null character
"Strings" (cont.)
Back SMYC Forward
// This statement will allocate memory for // an array of 17 character (16 for the "real" // characters and 1 for the null character) and // assign the characters 'C', 'o', ... '\0' to the // elements char department[] = "Computer Science";
The const Qualifier
Back SMYC Forward
  • Syntax:
    • The const qualifier can appear once in a declaration (but not after a comma)
  • Purpose:
    • Declares the entity to be non-modifiable (sometimes called "read-only")
  • Details:
    • For arrays, the elements are non-modifiable
    • For pointers, the entity being pointed to is non-modifiable
The const Qualifier (cont.)
Back SMYC Forward
const int i = 5; i = 10; // Will not compile const char *department; department = "Computer Science"; // Will compile department[0] = 'X'; // Will not compile department = "Mathematics"; // Will compile const double grades[] = {90., 75.}; grades[1] = 100.; // Will not compile char course[] = "C Programming"; course = "Data Structures"; // Will not compile because the // the RHS is const but the LHS is not const char grade[] = "B-"; grade = "B+"; // Will not compile because the // LHS is const (i.e., non-modifiable)
Address Arithmetic
Back SMYC Forward
  • The Philosophy:
    • Be consistent and regular; integrate pointers with arrays and address arithmetic
  • The Implications:
    • If p is a pointer to an element of an array then p++ increments p to point to the next element
Address Arithmetic and Arrays
Back SMYC Forward
// Allocate memory for and initialize the array double grades[] = {90., 75., 55.}; // Assig the address of (the first element of) the array to p double *p = grades; // Change element 0 the obvious way grades[0] = 100.; // Change element 1 a less obvious way (using the address arithmetic // performed by the [] operator p[1] = 100.; // Change element 2 a less obvious way (using explicit address arithmetic) p += 2; // Change the pointer (by the size of two doubles *p = 100.; // Assign 100.0 to the address (by dereferencing p)
Address Arithmetic, the const Qualifier and "Strings"
Back SMYC Forward
// This statement will assign the address of the "string" // "Computer Science\0" to the pointer department. char *department = "Computer Science"; // The above isn't safe because the following will compile // and, when executed, cause a problem (e.g., a segmentation fault) // because read-only memory is being written to department[0] = 'X'; // So, it's better to do the following const char *department = "Computer Science";
Functions
Back SMYC Forward
  • Purpose:
    • Encapsulate a computation
  • Syntax:
    • type name([type parameter]...){statement...}
Functions (cont.)
Back SMYC Forward
  • Return Values:
    • Typed functions indicate the value they evaluate to using a return statement
  • void Functions:
    • Have a void type and no return statement or a return statement with no expression
  • Functions with No Formal Parameters:
    • If the formal parameter list is empty then the actual parameter list needn't be (though the actual parameters will be ignored)
    • If the formal parameter list is void then the compiler will check to make sure the actual parameter list is empty
Invoking/Executing Functions
Back SMYC Forward
  • Syntax:
    • identifier([parameters])
  • Example:
    • size = area(10.2, 20.9);
Argument Passing
Back SMYC Forward
  • The Rule:
    • All arguments are passed by value
  • Getting Around the Rule:
    • Pass a pointer
    • Receive a pointer
  • Arrays:
    • When the name of an array is used as an argument, a pointer to the beginning of the array is passed
Pointers to Functions
Back SMYC Forward
  • Two Observations:
    • Functions are not variables
    • One can define pointers to functions
  • An Example:
    • void sort(void *data[], int (*comp)(void *, void *)) { // The body of the algorithm which can include statements like: if ((*comp)(data[i], data[i+1]) < 0) { } }
Structures
Back SMYC Forward
  • Defined:
    • A collection of one or more (possibly heterogeneous) variables
  • An Example:
    • struct employee { int age; double salary; };
  • Membership:
    • The Membership Operator: .
    • The Shorthand Operator: -> is short for (*pointer).member
typedef
Back SMYC Forward
  • Purpose:
    • Allows the creation of new data type names
  • Examples:
    • typedef int Length; typedef struct tnode *Treeptr; // A Treeptr is a pointer to a structure typedef struct tnode { // A Treenode is a structure char *word; int count; Treeptr left; Treeptr right; } Treenode;
Unions
Back SMYC Forward
  • Defined:
    • A variable that may, at different times, hold objects of different types and sizes
  • An Example:
    • union u_type { int ivalue; double dvalue; } u;
  • Intepretation:
    • u will be large enough to hold the larger of an int and double
More Advanced Topics
Back SMYC Forward
  • I/O
  • Scope, Duration and Linkage
  • Memory Management
  • Variadic Functions
There's Always More to Learn
Back -