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
struct
and 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
const
in 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:
auto
double
int
struct
break
else
long
switch
case
enum
register
typedef
char
extern
return
union
continue
for
signed
void
do
if
static
while
default
goto
sizeof
volatile
const
float
short
unsigned
Note: 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
: sizeof
order relations
: <
, <=
, >,
>=
reference and dereference
: &
, *
, [ ]
sequencing
: ,
subexpression grouping
: ( )
type conversion
: (
typename)
Here is an example program:
#include <stdio.h>
int main()
{
("Hello, World\n");
printfreturn 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()
{
("Hello, World");
putsreturn 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.c
Change default name:
$ gcc hello.c -o hello
Take advantage of “recent” improvements:
$ gcc –o hello –std=c99 hello.c
See more warnings:
$ gcc –o hello –std=c99 -Wall hello.c
Turn on light optimization (helps us see more warnings like uninitialized variables):
$ gcc –o hello –std=c99 -Wall -O1 hello.c
make
make
: Goes through a descriptor file starting with the target it is going to create.
Example: Minimal makefile
# 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.cclean: rm -f hello
- Now we can just do
make && ./hello
- We can also do
make clean
to delete thehello
file.
How make
Works:
makefile
and Makefile
.Note: Commands must be indented with tabs rather than spaces.
Example: Another Makefile
FLAGS = -std=c99 -Wall -O1 all: hello goodbye hello: hello.c goodbye.c gcc ${FLAGS} -o hello hello.c ${FLAGS} -o goodbye goodbye.c gcc clean: rm -f hello rm -f goodbye
printf
printf()
is a function provided by the standard I/O library (stdio.h
).
Example: Using
printf()
#include <stdio.h> int main() { char grade = 'A'; # Print a char ("Character grade is %c \n", grade); printf# Print a float float toll= 15.678; ("Toll value is %f \n", toll); printf# Print an int int x = 125; ("Integer x value is %d\n" , x); printf# Print a double double width= 23.123456; ("Double value is %lf \n", width); printf# Print an octal ("Octal value of x is %o \n", x); printf# Print a hexadecimal ("Hexadecimal value of is %x \n", x); printfreturn 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.
Example: Reading a character from
stdin
#include <stdio.h> int main() { char userChar; ("Please enter a character: "); puts("%c", &userChar); scanf("Your character: %c\n", userChar); printfreturn 0; }
Example: Doing math on user input.
#include <stdio.h> int main() { int x, y, z; ("Input three different integers: \n"); printf("%d %d %d", &x, &y, &z); scanf int SUM = x + y + z; float AVG = (SUM / 3); int PRODUCT = x * y * z; ("Sum: %d \n", SUM); printf("Average: %f \n", AVG); printf("Product: %d \n", PRODUCT); printfreturn 0; }
Example: Printing the squares and cubes of the first 10 positive integers.
#include <stdio.h> int main() { ("Number\tSquare\tCube\n"); printffor (int i = 1; i <= 10; i++) { int NUMBER = i; int SQUARE = i * i; int CUBE = i * i * i; ("%d\t%d\t%d\n", NUMBER, SQUARE, CUBE); printf} return 0; }
How-To Use:
#include <math.h>
-lm
option to gcc.gcc -o hello -std=c99 -O2 -lm hello.c
Common 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
Example: Seeding the random number generator with the machine’s current time.
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { (time(0)); srandint RANDOM = rand(); ("Random Number: %d", RANDOM); printfreturn 0; }
Example: Generating a random number in a range.
#include <stdio.h> #include <stdlib.h> #include <time.h> int main() { (time(0)); srandint RANDOM = 5+rand()%16; ("Random Number between 5 and 20: %d", RANDOM); printfreturn 0; }
stdlib.h
Communication 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.h
Comparison:
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.