개발/C·C++
-
Sequence point개발/C·C++ 2021. 3. 30. 16:39
쉼표 연산자의 왼쪽 피연산자, && 연산자의 왼쪽 피연산자, || 연산자의 왼쪽 피연산자 등이 시퀀스 포인트가 됩니다. 세미콜론도 포함됩니다. 시퀀스 포인트 안에서 변수 변경(연산)은 한 번만 이루어져야 합니다. 둘 이상은 계산 순서가 지정되어 있지 않은 undefined behavior입니다. docs.microsoft.com/ko-kr/cpp/c-language/c-sequence-points?view=msvc-160 C 시퀀스 위치 자세한 정보: C 시퀀스 위치 docs.microsoft.com dojang.io/mod/page/view.php?id=757
-
[cin] 입력 실패를 처리하는 법개발/C·C++ 2021. 3. 29. 23:09
문자 하나씩만 입력하면 문제가 없는데, 두 개 이상 입력하면 버퍼에 남아 있는 것이 차례대로 출력된다. ab를 입력하면 a, b가 출력되고 abc를 입력하면 ab가 출력된다. 아직 버퍼에 c가 남아 있지만 cin 객체를 두 번 호출했기 때문에 a, b만 나온다. 문자를 얼마나 입력하든 최초 입력하는 문자 하나만 출력하고 싶다면 어떻게 해야 할까. 쉽게 생각해서 두 번째부터 등장하는 문자는 모두 무시하면 된다. cin에 ignore() 함수가 있다. 첫 번째 인자는 무시할 갯수를 넣으면 되는데 어느 길이의 문자를 넣을지 모르기 때문에 정수로 표현할 수 있는 가장 큰 값을 넣어주자. limits 헤더를 인클루드해서 다음과 같이 사용해주면 된다. streamsize는 long long으로 최소 64비트 정수를..
-
가상 함수와 가상 함수 테이블개발/C·C++ 2019. 12. 11. 20:07
C++은 C에 객체지향 개념이 도입된 언어다. C++은 기본적으로 정적타입의 언어이기 때문에 컴파일 단계에서 변수의 타입을 결정한다. 실행 시간이 아니라 컴파일 시간에 오류를 발견할 수 있으므로 안정성이 좋다. 대신에 일단 컴파일이 끝나면 변경할 수 있는 것이 없다. 무언가 변경됐다면 컴파일을 다시 해야 한다. 적응성이 떨어질 수밖에 없다. 동적타입의 언어는 컴파일러가 없는 인터프리터 언어인 파이썬 등을 말하는데 실행 시간에 변수의 값에 의해 타입이 결정된다. 가장 큰 장점은 유연성이다. 대신에 문법적인 이해나 경험이 부족하다면 안정성을 보장할 수 없다. C++에서 virtual 키워드는 동적 바인딩을 위해 사용된다. 바인딩이란 프로그램 구성 요소의 성격을 결정해주는 것을 말하는데, C++은 정적타입의 ..
-
티스토리에 코드 넣기(SyntaxHighlighter)개발/C·C++ 2019. 11. 28. 18:26
검색해보면 작동도 안 하는데 작동하는 것처럼 올린 글도 것도 있고 설명이 2% 부족한 것도 있다. 설명이 잘된 사이트가 있어 기록용으로 남긴다. SyntaxHighlighter라는 프로그램을 활용할 것이므로 아래에서 다운받는다. 압축을 풀면 우리에게 필요한 폴더는 scripts랑 styles. 티스토리 [스킨편집]에서 [html 편집]으로 들어가 두 폴더에 있는 파일들을 업로드한다. 업로드가 끝나면 html에 추가할 내용이 있다. 1. 테마 테마를 어둡게 하고 싶어 다음 코드를 사이에 넣었다. 이 문장은 위치가 상관 없는데 식별하기 좋도록 바로 위에 넣었다. 테마는 stlyes 폴더에 있으며 어떤 모양새인지는 사이트에서 확인할 수 있다. 2. 언어 언어마다 조금씩 다른 스타일을 적용하기 위해서 넣는 코드..
-
BitConverter.ToIntXX() 함수 구현해보기개발/C·C++ 2019. 11. 6. 02:35
C#은 C++과 Java의 장점을 두루 갖고 있다. 비교적 늦게 태어난 언어인 만큼 단점보다는 장점이 더 많아 보인다. 네트워크 라이브러리 쓰기도 편하고 스레드도 지원을 잘한다. Java는 손을 뗀 지 조금 돼서 잘 모르겠는데, C#에는 여러 종류의 변환 함수를 지원한다. 문자열 변수를 바이트로 변환해준다든가(Encoding.UTF8.GetBytes(Name)), char형 배열에서 오프셋을 지정해 원하는 바이트만큼 읽어온다든가. 후자의 기능을 갖고 있는 함수가 BitConverter.ToIntXX() 계열의 함수다. 사실은 이 함수를 똑같이 구현하는 게 목적이 아니라 내부적으로 어떤 원리를 갖고 있는지 알아보려고 한다. 설명하려고 하는 함수는 가변 버퍼에서에서 발견할 수 있다. 서버 프로그래밍에서 가변..
-
윈도우 유저 모드 동기화 CRITICAL_SECTION개발/C·C++ 2019. 11. 4. 03:04
동기화 방법은 크게 유저 모드와 커널 모드가 있다. 커널 모드 동기화의 기능이 굳이 필요한 상황이 아니라면 유저 모드 동기화가 성능이 좋다. 응용 프로그램은 기본적으로 유저 모드에서 동작하기 때문에, 커널 모드 동기화를 사용하면 동기화할 때마다 커널에 접근해야 하므로 성능에 불이익이 생길 수밖에 없다. 유저 모드 동기화 방법은 주로 CRITICAL_SECTION(이하 CS)이 사용된다. 단순하게 변수의 정수값을 증감할 때는 Interlocked 계열 함수를 이용하면 되며 임계 영역을 동기화해야 하는 경우에는 CS로 동기화한다. CS로 동기화를 진행하기 위해서는 일단 CS 객체를 만들어야 한다. 초기화는 매개변수로 CS 객체의 포인터를 넣는 InitializeCriticalSection 함수를 사용하고 아..
-
뮤텍스와 WaitForSingleObject 함수개발/C·C++ 2019. 11. 1. 17:29
시스템 관련한 어느 책에서 뮤텍스 동기화를 설명하면서 WaitForSingleObject를 이용해 뮤텍스를 '획득'한다고 표현한다. CRITICAL_SECTION으로 유저 모드 동기화에도 거의 비슷한 표현을 하는데 잘 와닿지 않는다. 결과적으로는 획득이라는 표현은 아무 문제 없다고 반문한다면, 손가락이 언제나 달을 가리키고 있다고 해서 손가락을 보고 달이라고 할 수 없지 않은 것인가, 라고 대답하고 싶다. 뮤텍스를 생성하는 함수는 CreateMutex()로 세 개의 인자를 넣어줘야 한다. 그 중 두 번째 인자가 BOOL bInitialOwner로 TRUE를 넣으면 뮤텍스를 생성하는 스레드에서 해당 뮤텍스 사용하고 FALSE를 넣으면 어느 스레드가 되었던 먼저 사용하는 쪽이 임자다. 즉, TRUE에서는 뮤..
-
구조체 바이트 정렬은 만능이 아니다개발/C·C++ 2019. 10. 19. 17:13
pragma once에 이은 만능 시리즈는 아니다. 이 기능들을 별 생각 없이 사용했다가 뇌 곳곳에서 유혈이 낭자한 끝에 얻은 교훈을 남기고 싶을 뿐이다. 공교롭게 둘 다 pragma 키워드를 사용하는 것은 우연의 일치일까. 심도 있게 설명하고 싶지만 아직은 능력이 부족한 탓에 수박 껍질만 핥아보려고 한다. 핥핥핥. 제대로 된 실무 코드는 제대로 본 적이 없지만 소켓 프로그래밍에서는 패킷 헤더는 보통 구조체 바이트 정렬을 하는 것으로 보인다. 구조체 정렬은 함부로 쓰면 안 되지만 패킷 헤더에는 언제나 같은 크기의 데이터가 들어가(야 하)며, 동적으로 메모리를 할당할 일이 없기에 괜찮은 듯하다. 1 2 3 4 5 6 7 #pragma pack(push, 1) struct PacketHeader { shor..