Language/C
[따배씨] 16.3 #define 매크로
migrationArc
2021. 8. 5. 22:38
따배씨 - 따라하며 배우는 C언어
16강 전처리기와 라이브러리
16.3 #define 매크로
#include <stdio.h>
/*
Preprocessor directives begins with # simbol at the beginning of a line.
*/
/*
Macro
- An instruction that represents a sequence of instructions in abbreviated form.
*/
/*
#define SAY_HELLO printf("Hello, World!");
preprocessor Macro (name) body (or replacement list)
directive
Macro expansion - macro 가 body 의 내용으로 교체되는 것을 의미
*/
/*
Object-like macros vs Function-like macros
#define ONE 1
// 전처리기가 ONE 에 해당하는 부분을 1 로 교체, complier 입장에서는 변수는 아님
#define SQUARE(X) X*X
// compiler 입장에서는 함수가 아님, cpp 에서는 함수형 메크로 사용을 지양함
*/
#define PI 3.141592 /* Symbolic, or manifest, constans */
#define GRAVITY 9.8
#define THREE 3
#define MESSAGE "The greatst glory in living lies not in never falling, \
but in rising every time we fall."
#define NINE THREE*THREE
#define SAY_HELLO for(int i = 0; i < 10; i++) printf("Hello, World!\n");
#define FORMAT "Number is %d\n"
# define WITH_BLANK 1
#define MY_CH 'Z'
#define MY_ST "Z" // Z\0
#define LIMIT 20
const int LIM = 50;
static int arr1[LIMIT];
const int LIM2 = 2 * LIMIT;
/*
Tokens
#define SIX 3*2
#define SIX 3 * 2
#define SIX 3 * 2
*/
/* Redefining Constants */
#define SIX 2*3
#define SIX 2*3
// 한 file 안에서, define 을 여러번 선언 가능
// define 은 기본적으로 file scope
#define SIX 2 * 3 // Warning
#undef SIX
#define SIX 2 * 3
// undef 로 define 해제 후, 새롭게 define 하면 token 문제 해결 가능
int main()
{
int n = THREE;
SAY_HELLO
n = NINE;
printf(FORMAT, n);
printf("%s\n", MESSAGE); // replaced
printf("SAY_HELLO NINE\n"); // Not replaced
return 0;
}
- Macro 는 기본적으로 복사해서 붙여넣기 수준으로 교체해주는 것은 맞지만, 그렇지 않는 경우도 있으니 유의
- Compiler 는 Macro 의 내용을 알지 못함, 전처리기가 처리 하기 때문
#define SAY_HELLO for(int i = 0; i < 10; i++) printf("Hello, World!\n");
-
- SAY_HELLO 를 선언 할때, ';' (세미콜론) 을 붙였기 때문에, main 에서 SAY_HELLO 뒤에 ';' 을 붙이지 않아도 문제가 없다.
- 세미콜론이 두개가 붙여진다고 해서 문제가 생기는 것은 아님
- 오픈소스에서는 세미콜론을 안쓰는 경우가 많으므로 주의하자
- Macro 는 문자열 안에 있는 경우는 교체되지 않음
이 글의 모든 사진과 내용의 출처는 홍정모 교수님께 있음을 알려드립니다.
http://blog.naver.com/atelierjpro
실리콘 밸리의 프로그래머 : 네이버 블로그
안녕하세요! 홍정모 블로그에 오신 것을 환영합니다. 주로 프로그래밍 관련 메모 용도로 사용합니다. 강의 수강하시는 분들은 홍정모 연구소 카페로 오세요.
blog.naver.com
http://www.inflearn.com/course/following-c
홍정모의 따라하며 배우는 C언어 - 인프런 | 강의
'따배씨++'의 성원에 힘입어 새롭게 개발된 C 언어로 시작하는 프로그래밍 입문 강의입니다. '따배씨'와 함께 프로그래밍 인생을 업그레이드 해보세요., 따라하며 배우는 C언어 '따배씨++'의 성원
www.inflearn.com