JMU
The C Programming Language
An Introduction for Programmers


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Identifiers
Comments
Basic Data Types
Variables
Assignment Operator
Type Conversions
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
The if Statement
while Loops
do-while Loops
for Loops
Symbolic Names/Constants
Enumerations
Pointers
Arrays
Strings
"Strings" (cont.)
  // 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
The const Qualifier (cont.)
  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
Address Arithmetic and Arrays
  // 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"
  // 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
Functions (cont.)
Invoking/Executing Functions
Argument Passing
Pointers to Functions
Structures
typedef
Unions
More Advanced Topics