C

From cwhite's wiki
Jump to: navigation, search

Commands intended for the preprocessor are called directives

Simple C program example

directives

int main(void)
{
    statements
}

Making comments

/* This is a comment */
/* These are good */


/* Comments can
   extend multiple
   lines */

int main(void) /* They can also be on the same line as other program code */

// With C99, you can also use '//' at the beginning of the comment

// The C99 method does not require termination at the end of the comment

Variables and Assignment

Types
int - can be a whole number between 32,767 and 2,147,483,647
float - can support more numbers and use decimal values. Arithmetic on float variables may be slower than arithmetic on int variables

Declarations
Variables must be declared before they can be used:

int height;    /* The variable "height" with the type of "integer" */
float profit;    /* The variable "profit" with the type of "float" */

// If you have multiple variables with the same type, you can declare them on one line
int height, length, width, volume;
float profit, loss;

Assignment
After a variable is declared, it can be given a value

int height, length, width;
float profit;

height = 8;
length = 10;
width = 2;

float = 215.29f; /* Notice the "f" at the end of the number. This should be added
                    to values with a decimal in them else errors may arise */

Printing Variables
To print a integer, use %d. To print a float, use %f. By default, %f displays a number with six digits after the decimal point. To modify this behaviour, put a .p between % and f; for example:

float profit;
int height, width;

profit = 300.99

printf("Profit: %.2f\n", profit);

height = 2
width = 3

printf("The width is %d and the height is %d.", width, height);

Reading Input

To read an int value, we'd use scanf as follows:

scanf("%d", &i);    /* reads an int value; stores into i */

To read a float value, we'd use scanf as follows:

scanf("%f", &x);    /* reads a float value; stores into x */

Example, asking for user input:

#include <stdio.h>

int main(void)
{
    int height, length, width, volume, weight;

    printf("Enter height of box: ");
    scanf("%d", &height);
    printf("Enter length of box: ");
    scanf("%d", &length);
    printf("Enter width of box: ");
    scanf("%d", &width);

    volume = height * length * width;
    weight = (volume + 165) / 166;

    printf("Volume (cubic in): %d\n", volume);
    printf("Dimensional weight (lbs): %d\n", weight);

    return 0;
}

scanf("%f", &x);    /* reads a float value; stores into x */


Define Names for Constants

Macros definitions is a feature that allows you to name constant variables. #define is a preprocessing directive so there is no semi-colon at the end of the line. When a program is compiled, the preprocessor replaces each macro by the value that it represents

#define INCHES_PER_POUND 166

weight = (volume + INCHES_PER_POUND - 1) / INCHES_PER_POUND; /* Before preprocessor */

weight = (volume + 166 - 1) / 166; /* After preprocessor */

Identifiers

Identifiers are names we choose for variables, functions, macros, etc. They may contain letters, digits and underscores but must begin with a letter or underscore ("29variable" is not a valid identifier). Identifiers are of course case sensitive.



Functions

These sections go into a little bit more detail about various functions.

printf

printf is designed to display the contents of a string, known as the format string, with values possibly inserted at specified points in the string.

Syntax

printf(string, expr1, expr2, ...);

Conversion specification form
%m.pX
m is the minimum field width
p is precision and can vary depending on the conversion specifier
X indicates which conversion should be applied to the value before it's printed

m (minimum field width) specifies the minimum number of characters to print. If the value to be printed requires fewer than m characters, the value is right-justified within the field (space added before the value). Putting a - in front of the m will cause it to be left-justified (space added after the value).

p depends on the conversion specifier of X. See the conversion specifier section for more information.

X is the conversion specifier and indicated which conversion should be applied to the value before it's printed.

Conversion specifiers
  •  %d - Displays an integer in decimal form.
  •  %e - Displays a floating point number in exponential format. p indicates how many digits should appear after the decimal point (default 6). If p is 0, the decimal point is not displayed.
  •  %f - Displays a floating point number in fixed decimal format, without an exponent, p has the same meaning as the e specifier.
  •  %g - Displays a floating point number in either exponential format or fixed decimal format, depending on the number's size. p indicates the maximum number of significant digits (not digits after the decimal point) to be displayed. Unlike the f conversion, the g conversion won't show trailing zeros.


END OF printf

scanf

END OF scanf



Operators

Oh fun. Operators..

Operators
Precedence Name Symbol(s) Associativity
1 increment(postfix)
decrement(postfix)
++ left
2 increment(prefix)
decrement(prefix)
unary plus
unary minus
++
--
+
-
right
3 multiplicative * / % left
4 additive + - left
5 assignment = *= /= %= += -= right

Arithmetic Operators

Arithmetic operators perform addition, subtraction, multiplication and division.

Example calculates the check digit (last number) on UPC bar codes:

#include <stdio.h>

int main(void)
{
    int upc_1, i1, i2, i3, i4, i5, b1, b2, b3, b4, b5, sum_1, sum_2, check_digit;

    printf("What is the first digit of the UPC code? \n");
    scanf("%i", &upc_1);
    printf("What are the next five numbers?\n");
    scanf("%1d%1d%1d%1d%1d", &i1,&i2,&i3,&i4,&i5);
    printf("What are the last five numbers?\n");
    scanf("%1d%1d%1d%1d%1d", &b1,&b2,&b3,&b4,&b5);

    sum_1 = upc_1 + i2 + i4 + b1 + b3 + b5;
    sum_2 = i1 + i3 + i5 + b2 + b4;

    check_digit = (9 - ((((sum_1 * 3) + sum_2) - 1) % 10));

    printf("The check digit should be %d", check_digit);

    return 0;
}

END OF ARITHMETIC

Assignment Operators

v = e

If v and e are of different types, e is converted to the type of v as the assignment takes place.

int i;
float f;

f = i = 33.3f; /* i is assigned the value 33 and f is assigned the value 33.0 */


Assignment operators are right associative, for example:

i = j = k = 0;

/* Which is the equivalent to */

i = (j = (k = 0)); /* So 0 is assigned to k, then to j, then to i. */

L-Values The assignment operator requires an lvalue as its left operand. An lvalue represents an object stored in computer memory, not a constant or the result of a computation. Variables are lvalues; expressions such as 10 or 2 * i are not.

2 = i; /* INCORRECT */
i + j = 0; /* INCORRECT */
-i = j; /* INCORRECT */
i = 2; /* CORRECT */

Compound Assignment Compound assignment operators allow us to shorten arithmetic operations.

i = i + 2;

/* Is the same as */

i += 2;

Valid compound assignment operators are: += -= *= /= %=

END OF ASSIGNMENT

Increment and Decrement Operators

This is similar to "i +=1;" but this operand allows us to condense these statements a bit further with the ++ and -- operators. These operators can be used as prefix operators (++i and --i) or postfix operators (i++ and i--).

/* pre-increment example */

i = 1;
printf("i is %d", ++i);    /* print "i is 2" */
printf("i is %d", i);    /* print "i is 2" */

/* post-increment example */

i = 1;
printf("i is %d", i++);    /* print "i is 1" */
printf("i is %d", i);    /* print "i is 2" */

END OF Increment/Decrement

Relational Operators

Symbol Meaning
< less than
> greater than
<= less than or equal to
>= greater than equal to



Statements

There are a different types of statements

  • Selection statements: The if and switch statements allow a program to select a particular execution path from a set of alternatives.
  • Iteration statements: The while, do and for statements support iteration (looping).
  • Jump statements: The break, continue and goto statements cause an unconditional jump to some other place in the program.