[C] C 언어 시작하기

chohk10·2023년 3월 31일
0

C 언어

목록 보기
1/3
post-thumbnail

SW사관학교 정글 5주차에 접어들어 RB Tree 구현 과제가 주어졌는데, 생전 처음 다뤄보는 C언어로 구현을 하라고 한다. ChatGPT에게 일부 궁금한 내용들을 물어보며 가능한 빠르게 해당 언어에 익숙해져 보려고 한다.


우선, Harvard CS50 2019 강의 를 통해서 C 언어에 대해 알아보자.
- gcc, clang 모두 C언어 코드를 컴파일하는데 사용되는 컴파일러
- gcc -o(out) hello hello.c (생성되는 파일의 파일명을 지정)
- 파일명* : 별표가 있는 파일명은 executable file
- make [파일명] : 지정한 파일명으로 된 C 소스파일을 찾아서 필요한 argument를 알아서 지정한 후 compile 해줌 - Linux 기반 OS에 기본 제공되며, 요즘은 윈도우에도 있다고 함
- .h : headerfile - file with prototype functions(?)
- preprocessing --> compiling(into assembly code) --> assembling(into machine code) --> linking(all relevant assembled machine codes to make one executable object file)
- Debugger 는 내가 틀린 부분을 특정해서, 뭐가 잘못된 것 같은지를 알려주는 프로그램
- Useful info regarding style guides for C, third-party sw and more here.
- Rubber duck debugging : talk with your rubber duck verbally LOL


다음으로는 구체적인 C언어 사용법을 알아보자.

기본 구조

#include <stdio.h>

void main()
{
 printf("Hello, World!");
}

선행 처리기(Preprocessor)

컴파일러가 컴파일하기 전에 처리하는 기능

선행 처리기의 역할

  • 단순한 문자열 치환
  • 다른 파일의 내용을 병합
  • 컴파일러에게 컴파일 조건 부여
  • 컴파일러에게 정보 제공

선행처리기 지시자

  • # 부호로 시작
  • 여러개의 지시자 작성 시 각각 하나의 라인에 존재해야 함
  • 여러줄에 작성 시 \로 줄바꿈

#define

  • 매크로 상수 정의
  • 매크로 함수 정의

#include

  • #include <headername> : C의 표준 디렉토리에서 해당 헤더파일을 찾는다.
  • #include "headername" : 현재 디렉토리에서 해당 헤더파일을 찾는다.
  • #include <stdio.h> : 기본 입출력함수를 가지고 있는 C의 내장 파일을 로드 (standard io.h)

조건컴파일

  • 조건문이 참이면 컴파일을 하도록 하여 선택적으로 컴파일될 수 있도록 함
    #if, #elif, #else, #endif
  • 매크로 상수가 정의되어 있으면 컴파일
    #ifdef, #else, #endif
  • 매크로 상수가 정의되어 있지 않으면 컴파일
    #ifndef, #endif
  • 그 외
    #error, #undef, #line, #pragma

표준 매크로 (더 알아보기)

#와 ## 연산자 (더 알아보기)

Aside) main 함수의 return 값

printf("Hello") 를 실행하려고 하는데, main() 함수에 return 0의 의미가 뭔지 궁금해 GPT에게 물어보았다.

In C programming, the main() function is required to return an integer value to the operating system upon completion. This return value is used to indicate the success or failure of the program's execution.
Conventionally, a return value of 0 indicates that the program executed successfully without any errors or issues. This is the most common return value for a program that completes its task without any errors.
On the other hand, non-zero return values are used to indicate that the program encountered an error or issue during execution. The specific non-zero value returned can provide information about the nature of the error or issue.

Some common non-zero return values and their meanings are:

  • 1: Generally indicates that the program encountered some kind of user error, such as an invalid command-line argument or input file.
  • 2: Indicates that the program encountered some kind of internal error, such as a failure to allocate memory or a division by zero.
  • Other non-zero values: The specific value can vary depending on the program and the context, but generally indicates a specific type of error or issue.

It's important to note that the specific return values used can vary depending on the program and the context in which it is used. However, it is generally a good practice to follow the convention of using 0 to indicate successful completion and non-zero values to indicate errors or issues.

리턴값 0의 경우에는 conventional 하게 실행을 성공적으로 마친 경우를 의미한다. 그 외 0이 아닌 값들은 일반적으로 에러 또는 이슈를 의미한다고 한다. 위에 서술된 대로 각각의 프로그램에서 정의하는 바를 따라가는 것이 중요할 것 같다.
위의 예시에서는 1, 2값에 대해 일반적으로 부여되는 의미가 설명되고 있고, 현재 공부하고 있는 내용에서는 -1 등 음수값도 에러에 대한 리턴값으로 많이 쓰는 것 같다.

기타 기본적인 내용

출력함수 Printf()

printf 에서 f는 formatted 라는 뜻으로, 형식화된 텍스트를 출력한다는 의미를 가진다.

알고 있던 내용이긴 하지만 코드업으로 문제를 풀어보면서 이참에 한번 정리

이스케이프(escape) 문자

출력하는 문장 안에서 원하는 형식에 맞추어 출력할 수 있도록 줄을 바꾸는 등의 특별한 의미들을 나타내기 위해 사용된다.

  • \n : (new line) 줄 바꿈
  • \t : (tab) 탭
  • \r : (carriage return) 그 줄의 맨 앞으로 커서를 보냄
  • \', \" : 따옴표 출력
  • \\ : 백슬래시\ 출력
  • printf("hello\n") : hello와 개행을 출력

형식 지정자(format specifier, place holder)

% 기호가 앞에 붙는 문자를 형식 지정자(format specifier)라고 하며, 그 위치에서 지정한 형식으로 데이터를 출력할 수 있도록 지정하는 역할을 한다.

  • %d : (decimal) 10진수 정수형 데이터 출력
  • %f : (float) 실수형 데이터 출력
  • %c : (char) 문자형 데이터 출력
  • %s : (char*) 문자열 데이터 출력
  • %p : (void*) 주소값 출력
  • %[자릿수]형식지정자 : 자릿수 지정
  • %% : 퍼센트 문자% 출력
  • printf("%d\n", num) : num 변수에 담긴 int형 값을 출력

유니코드로 특수문자 출력

선문자 등 특수문자는 유니코드를 사용하여 출력한다.
(운영체제 또는 컴파일러에 따라 사용되는 문자의 코드표가 다르다.)

  • printf("\u250C\u252C\u2510\n"); : ┌┬┐

입력함수 scanf()

형식
scanf(서식, 변수의주소)

int [변수명];
scanf("%[형식지정자]", &[변수명]);
  • int scanf(char const * const _Format, ...);
  • 성공하면 가져온 값의 개수를 반환, 실패하면 EOF(-1)를 반환
  • 입력되는 값의 자릿수 등 서식을 지정할 수 있음
  • 변수명 앞에 붙여주는 &은 뒤에 따라오는 내용은 주소값임을 나타냄

형변환 Casting

ex) (int) variable : int 형으로 타입을 변환
ex) (void **)ptr : ptr 변수의 형을 더블 포인터로 형변환


참고
https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=bluegriffin&logNo=40064101860
https://heekng.tistory.com/35
https://dojang.io/mod/page/view.php?id=79

0개의 댓글