C basics
Variables:
----------
store a value of some type
name associated with storage location (use meaningful names)
need to be declared before used
variable names must start w/letter, not be any key words.
int x, z; /* allocate 2 int storage locations with names x and z */
float y; /* allocate a float storage location with name y */
char ch;
Data Types:
-----------
standard C types:
-----------------
type input a value output a value
---- ------------- --------------
int GetInteger() printf("%d", 2);
examples -1, 0, 1, 22
double GetReal() printf("%g", y);
float
examples 2.178, 3.14, -19.99
char printf("%c", ch);
examples 'a', '2', ':'
defined in genlib.h:
--------------------
type input a value output a value
---- ------------- --------------
bool no input routine no output routine
two possible values: TRUE, FALSE
bool b = TRUE;
standard C uses int values for true and false:
0 is false, any non-zero int value is true
Statements:
----------
(1) Function calls:
/* GetInteger and printf are functions */
x = GetInteger();
printf("%d\n", x);
(2) Assignment statements: variable = value of expression;
* an EXPRESSION represents a value
* need to be concerned with TYPE of an expression
var's type must match the type of the expression
exception: int expressions can be assigned to a float or a double var
and C will automatically convert it to float or double
float r;
r = 7; // 7 will be converted to 7.0 and assigned to r
C will let you assign a float or char expression to an int, but the
results may not be what you expect
assigning a real value to an int, the value is truncated leaving just whole number:
x = 5.99999; // x gets the value 5
x = -5.99999; // x gets the value -5
* must assign a variable a value before you can use it in an expression
(initialize variables before you use them)
int x, z;
x = 2; /* first initialize x */
z = 3 + x; /* now you can use it on the rhs of an assignment stmt */
* arithmetic expressions
(a) arithmetic operators: +, -, *, /, %
terms must be of same type (except int w/float or double automatically converted)
x = 6/4 vs. y = 6.0/4
can type cast to get correct type (these do not evaluate to the same value):
y = (double)(3/6); or y = ((double)3)/6;
^^^ ^^^
int division first recast 3 to double 3.0
then recast as a double then do double division
to get 0.0 to get 0.5
% operator: only for int operands, evaluates to the remainder part of division
7 % 2 evaluates to 1 ( 7 divided by 2 is 3 with a remainder of 1)
11 % 3 evaluates to 2 ( 11 divided by 3 is 3 with a remainder of 2)
(b) precedence rules
( )
function call
unary minus
*, /, % left to right
+ - left to right
left to right
(c) short hand:
x++ is shorthand for: x = x + 1
x op= expr is shorthand for: x = x op expr
(ex) x += 6; is shorthand for: x = x + 6;
(ex) x *= 7; is shorthand for: x = x * 7;