hello.c
#include <stdio.h>가장 먼저 세상에 인사하는 코드다. 위에서부터 살펴 보면, #include <stdio.h>는 기본적으로 사용할 함수가 들어 있는 C의 패키지를 호출한다. int main(void) { }로 코드 입력 장소를 초기화하고, 내부에 출력하고자 하는 문구를 printf( ) 함수 안에 넣는다. 마지막으로 ;(세미콜론)으로 닫아주면 "hello world"가 출력되는 c언어 파일이 생성된다. \n은 Escape 문자로, 개행을 의미한다. 개행은 해도 되고 안 해도 되는데, 출력 후 가독성을 위해 적는 것이 낫다.
int main(void) { printf("hello world\n"); }
컴파일러의 위치
Terminal
$ clang hello.c $ ./a.out hello worldclang으로 컴파일하면 기본적으로 a.out이라는 실행파일이 생성되고, 현재 디렉토리를 나타내는 ./과 함께 실행파일을 호출하면 소스코드에 구현된 기능이 실행된다. $ clang -o hello hello.c와 같이 -o 옵션을 활용해 임의로 파일명을 지정할 수도 있다. 그러나 이러한 옵션들을 일일이 붙이다 보면 명령어가 점점 길어진다. 그래서 간단하게 컴파일해주는 명령어도 존재한다.
Terminal
$ make hello대신 컴파일하려는 소스코드 파일명과 make의 파일명은 동일해야 한다. 그러면 컴퓨터가 알아서 같은 이름을 가진 .c를 찾아 컴파일하여 output을 만들어줄 것이다.
clang -fsanitize=signed-integer-overflow -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow hello.c -lcrypt -lcs50 -lm -o hello
$ ./hello
hello world
Terminal
$ ls // 현재 디렉토리 리스트
a.out* hello* hello.c // '*'은 실행 가능, 머신코드, 소스코드 구분 가능
$ rm a.out // 파일 삭제
rm: remove regular file 'a.out'? y // y or n
$ ls
hello* hello.c
$ cd 디렉토리 // 해당 디렉토리로 이동
$ cd ../ // 상위 디렉토리로 이동
$ clear // 터미널 내용 지움
string.c
#include <cs50.h> #include <stdio.h>다만, hello.c와 약간 코드가 다른데, <cs50.h> 패키지를 불러온다. main 안에 있는 get_string( )은 기본 패키지에 포함되어 있지 않기 때문에 해당 함수를 가진 패키지를 호출해야 동작한다. 출력에 있는 %s는 형식지정자로, 출력하고자 하는 변수가 어떤 자료형인지 알려주는 역할을 한다. 자료형에 따른 형식지정자는 (4) 자료형, 형식 지정자, 연산자에서 정리할 예정이다.
int main(void) { string answer = get_string("What's your name?\n"); printf("hello, %s\n", answer); }
Terminal
$ clang -o string string.c -lcs50패키지가 늘어날수록 컴파일 명렁어에 붙일 꼬리도 늘어나는 셈인데, make 하나면 깔끔하게 해결된다. 컴파일한 'string'을 실행한 결과는 아래와 같다.
$ make string
clang -fsanitize=signed-integer-overflow -fsanitize=undefined -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow string.c -lcrypt -lcs50 -lm -o string
Terminal
$ ./string
What's your name?
Real-Bird
hello, Real-Bird
ifelse.c
#include <cs50.h> #include <stdio.h>
int main(void) { int x = get_int("x: "); int y = get_int("y: "); if (x < y) //1번 조건 { printf("x is less than y\n"); //1번 결과 } else if (x > y) //2번 조건 { printf("x is not less than y\n"); //2번 결과 } else //나머지 조건 { printf("x is equal to y\n"); //나머지 결과 } }
Terminal
$ ./ifelseif는 1번 조건을 의미하고, else if 2번 조건을, else는 나머지 조건을 의미한다. 각각의 조건은 참일 때 중괄호 속 결과를 출력한다.
x: 3
y: 5
x is less than y
ifelse.c
#include <cs50.h> #include <stdio.h>while( )문은 괄호 속 조건이 참일 경우 무한히 반복되는 명령어다. 위 코드에서는 i가 50보다 작을 때까지, 즉 0~49까지 i의 크기를 확인하면서 "hello world"를 출력한다. i가 50이 되는 순간, 조건은 거짓이 되면서 반복을 종료한다.
int main(void) { int i = 0; while (i < 50) { printf("hello world\n"); i++; } for (int i = 0; i < 50; i++;) { printf("hello world\n"); } }
자료형 | 의미 | 예시 |
---|---|---|
bool | 불리언 표현 | True, False, 1, 0, yes, no |
char | 문자 하나 | 'a', 'Z', '?' |
string | 문자열 | |
int | 특정 크기 또는 특정 비트까지의 정수 | 5, 28, -3, 0 |
long | 더 큰 크기의 정수 | |
float | 부동소수점을 갖는 실수 | 3.14, 0.0, -28.56 |
double | 부동소수점을 포함한 더 큰 실수 | 3.14, 0.0, -28.56 |
형식 지정자 | 자료형 |
---|---|
%c | char |
%f | float, double |
%i | int |
%li | long |
%s | string |
calculate.c
#include <cs50.h> #include <stdio.h>
int main(void) { int x = get_int("x: "); int y = get_int("y: ");
printf("x + y = %i\n", x + y); // 더하기 printf("x - y = %i\n", x - y); // 빼기 printf("x * y = %i\n", x * y); // 곱하기 printf("x / y = %i\n", x / y); // 나누기 printf("x %% y = %i\n", x % y) // 나머지 }
Terminal
$ ./calculate논리 연산자 &&(그리고, and)와 ||(또는, or)도 있고, 조건문에서 사용한 비교 연산자도 있다.
x: 5
y: 10
x + y = 15
x - y = -5
x * y = 50
x / y = 0
x % y = 5
hellome.c
#include <stdio.h>
void hellome(int n);
int main(void) { hellome(3); }
void hellome(int n) { for (int i = 0; i < n; i++) { printf("hello, Real-Bird!\n"); } }
Terminal
$ ./hellome여기에는 몇 가지 규칙이 있다. C언어는 정직한 로직이라 위에서 아래로만 읽는다. 함수를 메인 위에 선언해두었다면 실행에 지장이 없겠지만, 만약 가독성을 목적으로 메인 아래로 빼놓는다면 에러가 발생한다. 때문에 위의 코드에서도 아무런 기능이 없는 함수를 일단 선언해 두었다.
hello, Real-Bird!
hello, Real-Bird!
hello, Real-Bird!
multiplication.c
#include <stdio.h>
int main(void) { for (int i = 2; i <= 9; i++) { for (int j = 1; j <= 9; j++) { printf("%i * %i = %i\n", i, j, i * j); } printf("\n"); } }
Terminal
$ ./multiplication
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
. . .
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
calcu.c
#include <stdio.h>
int main(void) { float x = get_float("x: "); float y = get_float("y: ");printf("%.15f\n", x / y);
}
Terminal
$ ./calcu소수점을 15자리까지 늘려 확인해보니 0.1이 요상한 꼬리를 달고 있다. 이러한 현상은 float에 저장되는 부동소수점 비트가 유한하기 때문에 발생한다.
x: 1
y: 10
0.100000001490116
출처: 《부스트코스》 CS50 2-4