Why C?
Intro for C++ Programmers (C++ v.s. C):
“You can do OOP in C, but not cleanly, and why would you want to?”
C++ -> C:
- Classes and Member Functions.
- Use
structand global functions.- Derived Classes and Virtual Functions.
- Use
struct, global functions, and pointers to functions- Templates and Inline Functions
- Use macros
- Exceptions
- Use error-codes, error-return values, etc.
- Function Overloading
- Give each function a separate name
new/delete
- Use
malloc()/free()- References
- Use pointers
constin constant expressions
- Use macros
Missing in C:
- No class, only
struct- No methods. No constructors. No destructors.
- No
private/protected.- No
string,iostream,ifstream,vector…- No overloading of operators
- No overloading of functions
<<and>>have nothing to do with I/O!- No templates, STL,…
- No inheritance
In 1978, the first book of C programming, The C Programming Language, was published.
ANSI C:
C18/C17:
autodoubleintstructbreakelselongswitchcaseenumregistertypedefcharexternreturnunioncontinueforsignedvoiddoifstaticwhiledefaultgotosizeofvolatileconstfloatshortunsignedNote: C is a case-sensitive language, so all keywords must be written in lowercase.
arithmetic: +, -, *, /, %assignment: =augmented assignment: +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=bitwise logic: ~, &, |, ^bitwise shifts: <<, >>boolean logic: !, &&, ||conditional evaluation: ? :equality testing: ==, !=calling functions: ( )increment and decrement: ++, --member selection: ., ->object size: sizeoforder relations: <, <=, >, >=reference and dereference: &, *, [ ]sequencing: ,subexpression grouping: ( )type conversion: (typename)Here is an example program:
#include <stdio.h>
int main()
{
printf("Hello, World\n");
return 0;
}stdio.h: The standard input/output library.#include preprocessor.printf() is defined in here.return 0: Exit with code 0.printf(): Sends formatted output to stdout.Hello, World\n” is a character string or string constantHere’s another example program:
#include <stdio.h>
int main()
{
puts("Hello, World");
return 0;
}puts(), which prints a string to stdout with a newline.Note on Comments: Some versions of C only support multi-line comments (
/* */), though C99 added support for single-line comments (//)
Simplest:
$ gcc hello.cChange default name:
$ gcc hello.c -o helloTake advantage of “recent” improvements:
$ gcc –o hello –std=c99 hello.cSee more warnings:
$ gcc –o hello –std=c99 -Wall hello.cTurn on light optimization (helps us see more warnings like uninitialized variables):
$ gcc –o hello –std=c99 -Wall -O1 hello.cmakemake: Goes through a descriptor file starting with the target it is going to create.
# Makefile
all: hello
# This line says that hello.c is a dependency of hello
hello: hello.c
# Make runs this only if ./hello has a timestamp older than hello.c
gcc -o hello -std=c99 -Wall -O1 hello.c
clean:
rm -f hellomake && ./hellomake clean to delete the hello file.How make Works:
makefile and Makefile.Note: Commands must be indented with tabs rather than spaces.
FLAGS = -std=c99 -Wall -O1
all: hello goodbye
hello: hello.c goodbye.c
gcc ${FLAGS} -o hello hello.c
gcc ${FLAGS} -o goodbye goodbye.c
clean:
rm -f hello
rm -f goodbyeprintfprintf() is a function provided by the standard I/O library (stdio.h).
printf()#include <stdio.h>
int main()
{
char grade = 'A';
# Print a char
printf("Character grade is %c \n", grade);
# Print a float
float toll= 15.678;
printf("Toll value is %f \n", toll);
# Print an int
int x = 125;
printf("Integer x value is %d\n" , x);
# Print a double
double width= 23.123456;
printf("Double value is %lf \n", width);
# Print an octal
printf("Octal value of x is %o \n", x);
# Print a hexadecimal
printf("Hexadecimal value of is %x \n", x);
return 0;
}| Format Specifier | Description |
|---|---|
| %d | value of an integer variable |
| %c | value of a character variable |
| %f | value of a float variable |
| %lf | value of a double variable |
| %s | value of a string variable |
| %o | octal value corresponding to integer variable |
| %x | hexadecimal value corresponding to integer variable |
| % | newline character |
| Escape Sequence | Description |
|---|---|
| Newline. Position cursor to the beginning of the next line. | |
| Horizontal tab. Move cursor to the next tab stop | |
| Carriage return. Position cursor to the beginning of the current line; do not advance to the next line | |
| Alert. Sound the system bell | |
| \ | Backslash. Used to print a backslash character |
| ’ | Single quote. Use to print a single quote character |
| ” | Double quote. Used to print a double quote character |
scanf()scanf(): Function to read character, string, numeric data from keyboard.
stdin#include <stdio.h>
int main()
{
char userChar;
puts("Please enter a character: ");
scanf("%c", &userChar);
printf("Your character: %c\n", userChar);
return 0;
}#include <stdio.h>
int main()
{
int x, y, z;
printf("Input three different integers: \n");
scanf("%d %d %d", &x, &y, &z);
int SUM = x + y + z;
float AVG = (SUM / 3);
int PRODUCT = x * y * z;
printf("Sum: %d \n", SUM);
printf("Average: %f \n", AVG);
printf("Product: %d \n", PRODUCT);
return 0;
}#include <stdio.h>
int main()
{
printf("Number\tSquare\tCube\n");
for (int i = 1; i <= 10; i++)
{
int NUMBER = i;
int SQUARE = i * i;
int CUBE = i * i * i;
printf("%d\t%d\t%d\n", NUMBER, SQUARE, CUBE);
}
return 0;
}How-To Use:
#include <math.h>-lm option to gcc.gcc -o hello -std=c99 -O2 -lm hello.cCommon Functions:
| Function | Description |
|---|---|
acos | Arc cosine |
acosh | Hyperbolic arc cosine |
asin | Arc sine |
asinh | Hyperbolic arc sine |
atan | Arc tangent |
atan2 | Arc tangent and determine quadrant using sign |
atanh | Hyperbolic arc tangent |
cbrt | Cube root |
ceil | Nearest integer greater than the argument |
cos | Cosine |
cosh | Hyperbolic cosine |
exp | Exponential |
fabs | Absolute argument of floating point argument |
floor | Nearest integer lower than the argument passed |
hypot | Square root of sum of two arguments (hypotenuse) |
log | Natural logarithm |
log10 | Logarithm of base 10 |
pow | Number raised to given power |
sin | Sine |
sinh | Hyperbolic sine |
sqrt | Square root |
tan | Tangent |
tanh | Hyperbolic tangent |
srand and rand)srand(): Seeds the pseudo random number generator used by the rand()
stdlib.h#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(0));
int RANDOM = rand();
printf("Random Number: %d", RANDOM);
return 0;
}#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(0));
int RANDOM = 5+rand()%16;
printf("Random Number between 5 and 20: %d", RANDOM);
return 0;
}stdlib.hCommunication with the Environment:
abort: Abort program.atexit: Register function called at program exit.exit: Exit from a program.getenv: Get environment string.system: Perform operating system command.Integer Arithmetic:
abs: Absolute value of integerdiv: Integer divisionlabs: Absolute value of long integer.ldiv: Long integer division.String Conversion:
atof: Convert string to floating pointatoi: Convert string to integeratol: Convert string to long integerstrtod: Convert string to doublestrtol: Convert string to long integerstrtoll: Convert string to long longstrtoul: Convert string to unsigned long integerDynamically Allocated Arrays:
calloc: Allocate and clear memory block.malloc: Allocate memory block.realloc: Resize memory block.Deallocating Storage:
free: Free memory blockSearching and Sorting Functions:
bsearch: Binary searchqsort: Sort arraystring.hComparison:
memcmp: Compare memory blocksstcmp: String comparestrcoll: String compare using locale-specific collating sequencestrncmp: Bounded string comparestrxfrm: Transform locale-specific string.Search:
memchr: Search memory block for character.strchr: Search string for characterstrcspn: Search string for initial span of characters not in setstrpbrk: Search string for one of a set of charactersstrrchr: Search string in reverse for characterstrspn: Search string for initial span of characters in setstrstr: Search string for substringstrtok: Search string for tokenstrcat: Search string for concatenationstrncat: Search string for bounded string concatenationCopying:
memcpy: Copy memory blockmemmove: Copy memory blockstrcpy: String copystrncpy: Bounded string copyMiscellaneous:
memset: Initialize memory block.strerror: Convert error number to string.strlen: String length.