C Primer CAS CS210 Ying Ye Boston University

advertisement
C Primer
CAS CS210
Ying Ye
Boston University
Outline
 Hello, world
 Basics in C
 Comparison of C and Java
Getting started
 Open PuTTY, connect to csa2
 In your terminal, type in:
 cd ~/Desktop
 wget http://cs-people.bu.edu/yingy/hello.c
 vim hello.c
Hello, world
 #include <stdio.h> tells compiler to add a library(stdio) into the
program
Why? ==> printf()
 int main(void):
 program begins executing from main
 equivalent to main(), but more standard:
 int main(void);
 int main(int argc, char *argv[]);
Hello, world
 printf("hello, world\n") prints out the character string passed to
it
 return 0:
 return value required by main() function
 some compilers(like gcc) can add "return 0" automatically if
your main function doesn't return a value(only in main
function)
Hello, world
 Type in:
gcc hello.c
 Try: ls
 Run: ./a.out
 Want to specify the name? Try:
gcc -o XXX(name you like) hello.c
e.g. gcc -o abc hello.c
 Try ls again
Basics in C
 Basic types
Datatype
Size
Range
char
1
-128 to 127
short
2
-32768 to 32767
int
4
-2,147,483,648 to 2,147,483,647
long
4
-2,147,483,648 to 2,147,483,647
float
4
3.4*10+/-38
double
8
1.7*10+/-308
(In 32-bit machine!)
 Arrays
Basics in C
 Operators
 Arithmetic:
 ++, - +, -, *, /, %
 Relational:
 >, <, <=, >=, ==, !=
 Logical:
 &&, ||, !
 Bitwise:
 &, |, ^, <<, >>, ~
 Assignment:
 =, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=
Basics in C
 Control flow
 if...else
 switch
 while
 do...while
 for
 continue/break
Basics in C
 Functions
 Definition:
return-type function-name(parameter declarations)
{
declarations
statements
}
 Note: If you want to use a function before you define it in the
source code, you should declare the function before using it.
Example: C textbook page 24
Basics in C
 Call by value:
void swap(int a, int b)
{int c = a; a = b; b = c;}
int main(void)
{
int x = 1, y = 2;
swap(x, y);
return 0;
}
C and Java
{
for(int i = 0; i < 10; i++)
printf("hello, world\n");
return 0;
}
Add an option in gcc: gcc -o XXX -std=c99 hello.c
{
int i;
for(i = 0; i < 10; i++)
printf("hello, world\n");
return 0;
}
C and Java
 Uninitialized variables:
 In Java:
Instance variables initialized to 0, null, or false
 In C:
Initialized to random values
 No exceptions in C: return specific value to indicate error
 No string data type in C: use arrays to store character strings
e.g. char name[5] = {'J', 'o', 'h', 'n', '\0'};
Macros
 Definition: A macro is a fragment of code which has been given
a name. Whenever the name is used, it is represented by the
contents of the macro.
#define macro_name contents_of_macro
 Usages:
 Define a number as a macro: #define TOTAL 100
int a = TOTAL;
 Define a character string: #define NAME "John"
printf(NAME);
 Define a function: #define ADD(a, b) a += b
int x = 1, y = 2;
ADD(x, y);
Download