Introduction
First Program
#include <stdio.h>
int main()
{
printf("Rust is not good enough!");
return 0;
}
Detect the version of C
#include <stdio.h>
int main(int argc, char **argv) {
#if __STDC_VERSION__ >= 201710L
printf("We are using C18!\n");
#elif __STDC_VERSION__ >= 201112L
printf("We are using C11!\n");
#elif __STDC_VERSION__ >= 199901L
printf("We are using C99!\n");
#else
printf("We are using C89/C90!\n");
#endif
return 0;
}
Comments
/*
multiline comment
*/
// single line comment
Taking command line arguments
#include <stdio.h>
int main(int argc, char *argv[])
{
int numberOfArgs = argc;
char *argument = argv[0];
char *argument2 = argv[1];
printf("Number of arguments: %d\n", numberOfArgs);
printf("Argument number 1 is the program name: %s\n", argument);
printf("Argument2 is the command line argument: %s\n", argument2);
return 0;
}
NULL "\0"
A special character with the code value 0 is added to the end of each string to mark where it ends.
A string is always terminated by a null character so the length of a string is always one greater than the number of characters in the string that's why "length - 1" is commonly used.
Modular programming
We can put our code in multiple separate files and include the headers in the main file and use another source file to import functions and other instructions.
To do this:
Create a header file pointing to a source file:
Create other.h → header file.
#ifndef UNTITLED_OTHER_H
#define UNTITLED_OTHER_H
int getme(void);
#endif // UNTITLED_OTHER_H
Create the source file for the header:
Create other.c → source file for header.
int getme(void){
return 3;
}
Here we define the getme() function which was referred to by header and will be used in the main.c source file.
Include the header in main.c and use the function:
Create main.c, include other.h, and use getme() function.
#include <stdio.h>
#include "other.h"
int main(){
printf("%d\n", getme());
return 0;
}
Here we have to include the header file with "double quotations" cause we know its in the same directory so we don't need to look for it in the whole system.
To compile without an IDE from command line & compile all .c source files, headers are checked in compile time and are not included in the command:
gcc *.c -o [program name].
Last updated