C Programming
main()
All C programs should contain a main() function that follows the format
<optional return value type> main(<optional argument>) {
<optional procedure statements or functional calls>;
}
// argc integer holds the number of arguments
// argv holds the input arguments (strings)
// Name of the program is always stored at offset argv[0]
<optional return value type> main(int argc, char * argv[]){
}
Functions
Functions are self-contained bundles of code that can be called for execution by main()
// C Function format
<optional return value type> function name (<optional function argument>) {
}
// Simple example
#include <stdio.h>
#include <stdlib.h>
int foo() {
return 8;
}
int main(void){
int val_x;
val_x = foo();
printf("The value returned is: %d\n", val_x);
exit(0);
}
Variables
Used in programs to store pieces of information that may change and may be used to dynamically influence the program.
int
Stores a signed integer value such as 314 or -314
8 bytes for 64-bit machines
4 bytes for 32-bit machines
2 bytes for 16-bit machines
float
Stores a signed floating-point number such as 3.234
4 bytes
double
Stores a large floating-point number
8 bytes
char
Stores a single character
1 byte
printf
Prints out to the screen
// Trwo forms of the printf command:
printf(<string>);
printf(<format string>), <list of variables/values>);
%n
Print nothing
printf("test %n");
%d
Decimal value
printf("test %d, 123);
%s
String Value
printf("test %s", "123");
%x
Hex value
printf("test %x", 0x123);
%f
Float
printf("test %f", 1.308);
// Format string example code
#include <stdio.h>
int main(void){
double x = 23.5644;
//Total width of 5 with 2 values after the floating point
printf("The value of x is %5.2f\n", x);
// Total width of 4 with 1 value after the floating point
printf("The value of x is %4.1f\n", x);
return 0;
}
scanf
Generally used to get input from the user
// scanf format
scanf(<format string>, <list of variables/values>);
// Example - reads an integer from the user and stores it in a variable called number
scanf("%d", &number);
// You must use & before any variable with scanf
strcpy/strncpy
One of the most dangerous functions used in C.
Purpose is to copy each character in the source string into the destination string.
Dangerous because there is no checking of the source's size before it is copied over to the destination.
If the source is is larger than space allocated for the destination, overflow conditions are likely.
// Format
strcpy(<destination>, <source>);
strncpy is a safer alternative
// strncpy format
strncpy(<destination>, <source>, <width>);
Last updated