CSC 234

Basic C

v  Some Notes

  • C is case sensitive (so is UNIX/LINUX)
  • All programs have one entry point.
  • Instructions are performed in order.

#include <stdio.h>

int main (void)

{

int num;

printf(“Enter a number: “);

scanf(“%d”, &num);

num = num + 5;

printf(“Your number plus five is: %d”, num);

return 0;

}

Style and Whitespace

Style: The use of whitespace, location and amount of commenting, location of braces and other delimiting characters. It is how your code looks.

A good style is:

  • Easy to read
  • Easy to maintain
  • Shows what you were thinking when you wrote the code

Whitespace is for visual purposes only. The compiler strips it out. Use whitespace!

v  Keywords

Keywords are reserved words that the compiler knows about.

  • You can’t use them as variable names
  • Examples: if, while, for, return, int, float, void, do, switch, define, include

v  Data Types

Ways to represent information:

  • Integer:
  • int (32 bits: -2147483647 to 21474836)
  • Floating point, for example 34.556
  • double (64 bits)
  • Character (just a number used to represent a character in the ASCII table)
  • char (8 bit: -127 to 127)

v  Variables

Variables have a name, data type, and (optionally) an initial value.

  • float price;
  • int numStudents = 10;

Variable lifecycle:

  • declaration
  • initialization
  • use

v  Indentifiers

Uses:

  • variables
  • function names

Rules:

  • Use only letters, numbers, and underscores
  • Can’t start with a digit
  • Can’t use a reserved word
  • Don’t redefine standard identifiers (printf)

For this class,

Do this: numSiblings

Not: num_siblings

v  Operators

Perform some computation on a variable.

We have operators for:

  • Assignment (=)
  • Arithmetic (+, -, *, /, %)
  • Logic (&, ||, !)
  • Comparison (<, <=, >, >=, ==, !=)
  • Bit manipulation (don’t worry)

Operator Precendence:

v  Comments

/* I am a comment. Use me! */

Do not use comments to explain what a line of code does. Comment “blocks” of code.

Example:

/* get index choice */

printf("Which Recipe? ");

do{

scanf("%d", &index);

} while(index >= numRecipes || index <= -1);

v  Function Calls

“Calling” a function: transfers control of the program to another place, does something, then comes back to the main execution path.

Functions are used for repeated operations, complex calculations, and program maintainability.

The C library has many functions (printf, scanf, etc.) , and you can define your own.

Common C Mistakes

Syntax errors:

No semicolon, misspelling/not declaring an identifier, not closing comments, declaring a variable after an executed statement. The program won’t compile. There is no executable to run.

Runtime errors:

Divide by zero, forgetting & or * when using scanf.

Logic errors:

Confusing <= with <, or >= with >, or just getting them wrong altogether.