C Basics

From Wiki
Jump to navigation Jump to search

Reference: http://publications.gbdirect.co.uk/c_book/

Example Program

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]){
    printf("Enter your name: ");
    char name[64] = "";
    scanf("%s", name);
    printf("Hi there, %s!\n", name);
}

compile with

$ gcc test.c -o test

Comments

# /* hi there
#  *  here is my multi-line comment
#  */

Preprocessor directives

Include another entire file

#include <stdio.h>

Symbol replacement:

#define PI 3.1.41592
circumference = 2*PI*radius;

Function declaration and definition

If you want a function to be available to other files, declare its prototype in a myprogram.h file:

int make_an_int(int);   /* function prototype

Define it in the myprogram.c file:

int make_an_int(int my_arg){
    return my_arg + 10;
}

A function that takes no argument and returns nothing:

void do_nothing(void);   /* declaration/prototype */
void do_nothing(void){}  /* definition must have curly braces, no semicolon required*/

In the body of a function, all variables must be declared before any statements show up. Variable declarations may include assignment to a literal.

The main() function

int main(){...}

Set the return value to 0 to indicate success; set the return value to something else to specify an error.

Strings

Multi-line string literals:

"This would not be valid but doesn't have \
 a newline in it as far as the compiler is concerned"

String literals with only white space in between are concatenated:

"All this " "comes out as "
 "just one string"