Microsoft MVP성태의 닷넷 이야기
VC++: 154. C/C++ 언어의 문자열 Literal에 인덱스 적용하는 구문 [링크 복사], [링크+제목 복사],
조회: 16683
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

C/C++ 언어의 문자열 Literal에 인덱스 적용하는 구문

다음의 C 코드를 보면,

filtering_video.c
; https://ffmpeg.org/doxygen/trunk/filtering_video_8c-example.html

재미있는 구문이 하나 나옵니다. ^^

static void display_frame(const AVFrame *frame, AVRational time_base)
{
    // ...[생략]...
 
    /* Trivial ASCII grayscale display. */
    p0 = frame->data[0];
    puts("\033c");
    for (y = 0; y < frame->height; y++) {
        p = p0;
        for (x = 0; x < frame->width; x++)
            putchar(" .-+#"[*(p++) / 52]);
        putchar('\n');
        p0 += frame->linesize[0];
    }
    fflush(stdout);
}

처음엔 저 코드를 보고 putchar에 쓰인 탓에 C/C++ 언어 표준에 추가된 뭔가 새로운 format specifier 또는 String interpolation 방식인가 싶었습니다. 어쨌든, 정석적으로 해석해서 문자열 리터럴을 배열로 취급해 인덱스 접근하는 것임을 알게 되었는데요, C# 코드로 옮기면 다음과 같은 식입니다.

Console.WriteLine("Hello World"[0]); // 출력 결과: H

혹시, 이 구문이 초기부터 가능했는지 후에 추가된 표준인지 아시는 분이 계실까요? ^^ 이에 대해 검색해 보면,

Introduction to C / C++ Programming - Character Strings
; https://www.cs.uic.edu/~jbell/CourseNotes/C_Programming/CharacterStrings.html

1996년에 출간된 "C Programming, A Modern Approach" 책의 내용을 정리한 것이라고 하는데, 그렇다면 C99 표준 이전에 있었다는 것으로 아마도 초기 C 언어부터 제공된 문법이 아닐까 싶습니다.

단지, 저도 한 번도 써본 적이 없어서... ^^;




참고로, "filtering_video.c" 소스 코드에는 한 가지 더 특이한 코드가 있습니다.

puts("\033c");

재미있는 건, 위의 코드 그대로 검색해도 답변이 나온다는 것입니다. ^^

What does printf("\033c" ) mean?
; https://stackoverflow.com/questions/47503734/what-does-printf-033c-mean

정리해 보면, VT100 터미널에서 정의한 Control Character인데, 033 8진수가 escape 문자 역할을 하고 이후 'c' 글자로 기능을 선택합니다. 지원하는 기능은 다음의 문서에 나오는데,

ANSI/VT100 Terminal Control Escape Sequences
; https://web.archive.org/web/20190624214929/http://www.termsys.demon.co.uk/vtansi.htm

따라서 "Reset Device <ESC>c - Reset all terminal settings to default."에 해당합니다. 물론 VT100 터미널이라면 "settings"에 좀 더 많은 의미가 있겠지만, 단순히 윈도우 운영체제라면 "clear screen"으로 이해하셔도 무방합니다.

따라서, puts("\033c"); 코드는 윈도우 환경의 콘솔에서 실행하는 경우라면 system 함수를 호출해야 합니다.

// puts("\033c");
// C#의 경우, Console.Clear();

system("cls");

반면 리눅스의 경우에는 puts("\033c"); 코드가 잘 동작합니다. 실제로 (WSL 상관없이) ubuntu에서 아래의 명령을 내리면,

$ echo -e "\033c"

화면이 깨끗하게 지워지는 것을 볼 수 있습니다.




마지막으로, "filtering_video.c" 소스 코드를 비주얼 스튜디오 환경에서 컴파일하면 C4576 오류가 발생합니다.

if (frame->pts != AV_NOPTS_VALUE) {
	if (last_pts != AV_NOPTS_VALUE) {
		/* sleep roughly the right amount of time;
			* usleep is in microseconds, just like AV_TIME_BASE. */
		delay = av_rescale_q(frame->pts - last_pts,
			time_base, (AV_TIME_BASE_Q));
		if (delay > 0 && delay < 1000000)
			usleep(delay);
	}
	last_pts = frame->pts;
}

// Error C4576 a parenthesized type followed by an initializer list is a non-standard explicit type conversion syntax

AV_TIME_BASE_Q는 매크로 함수로 결국 "(AVRational){1, AV_TIME_BASE}" 코드로 변환되는데, 이것은 Compund Literals 문법에 해당하므로, 파일의 확장자를 ".c"로 변경하든가, 컴파일 옵션에 "/TC"를 추가해야 합니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 2/24/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2022-02-24 10시26분
[이승준] 아마 생각 하셨을것 같은데요.
ffmpeg의 모든 소스는 c입니다. c++ 아니고요.
그래서 쓰기가 번거로운면이 없잖아 있습니다.

사실 libxxx 이런식으로 시작하는 대부분의 오픈소스 라이브러리가 c기반이더군요.
엮시나 쓰기가 참 번거롭습니다.
[guest]

... 181  182  183  184  185  186  187  188  189  190  191  [192]  193  194  195  ...
NoWriterDateCnt.TitleFile(s)
245정성태6/1/200629365오류 유형: 3. [C# / VC++] error C2146: syntax error : missing ';' before identifier 'GetType'
247정성태5/3/200626780    답변글 .NET Framework: 3.1. Interface를 사용하면. [1]
242정성태6/1/200627159오류 유형: 2. [COM+] CreateObject 와 HTTP 500 - Internal server error
243정성태6/1/200624556    답변글 오류 유형: 2.1. [COM+] Resolve Partial Assembly failed for Microsoft.VC80.CRT.mui
244정성태6/1/200626067    답변글 오류 유형: 2.2. [COM+] Server object error 'ASP 0178 : 80070005'
240정성태6/1/200623904스크립트: 9. setTimeout 과 jscript/vbscript 혼용 문제
239정성태6/1/200624932COM 개체 관련: 18. Internet Explorer는 Out-of-process COM 개체입니다.
238정성태6/1/200626877개발 환경 구성: 1. batch 파일에서 실행한 exe에서 batch 실행 문맥의 환경 변수 설정 [3]
236정성태6/1/200647745오류 유형: 1. [.NET COM+] UnauthorizedAccessException: 레지스트리 키 HKEY_CLASSES_ROOT\.... 에 대한 액세스가 거부되었습니다
235정성태6/1/200622284VS.NET IDE: 39. VS.NET 2003/2005에서도 제공되는 VS 6.0 MFC ClassWizard
234정성태4/14/200621932VC++: 24. error C2039: 'pOleStr' : is not a member of '_STRRET'
233정성태4/13/200621303.NET Framework: 70. Response.ContentType 과 Response.AddHeader( "Content-Type", "..." ) 의 차이
232정성태4/13/200621193.NET Framework: 69. Reusing C# Source Code Across Multiple Assemblies
231정성태4/13/200621516Team Foundation Server: 4. How to rename a Team Foundation Server
229정성태10/17/200623109.NET Framework: 68. Feb CTP 에서 동작하는 "Save XPS Document page(s) to .bmp" 예제 소스
230정성태4/13/200623550    답변글 .NET Framework: 68.1. -01 MSDN Magazine XPS Document 소스를 Feb CTP로 수정한 버전파일 다운로드1
228정성태4/13/200619659Team Foundation Server: 3. MSBUILD : warning : Visual Studio Team System for Software Testers or Visual Studio Team System for Software Developers is required to run tests as part of a Team Build.
227정성태4/13/200621146Team Foundation Server: 2. TFS 빌드 오류 유형 - MSBUILD: warning : Specified cast is not valid
226정성태4/13/200618889Team Foundation Server: 1. TFS 오류 유형 - TF50608: Unable to retrieve information for security object
225정성태10/17/200618683.NET Framework: 67. VS.NET 2005 도구 상자에 있는 Workflow Activity 항목의 아이콘 변경
223정성태4/13/200630014.NET Framework: 66. Microsoft .NET Framework 2.0 Configuration 수동 설치파일 다운로드1
224정성태4/13/200624160    답변글 .NET Framework: 66.1. "Microsoft .NET Framework 2.0 Configuration" MSI 설치 파일 버전파일 다운로드1
222정성태4/13/200622566.NET Framework: 65. VS.NET 2005: 파일 기반 웹 프로젝트의 "Virtual Path" 제거
220정성태4/13/200620576.NET Framework: 64. ClickOnce - 배포 시 오류 : "Error: An unexpected error occurred -- The parameter is incorrect."
219정성태4/13/200635360.NET Framework: 63. ClickOnce - 최초 실행 시 보안 경고창 없애는 방법 [1]
216정성태4/13/200622325스크립트: 8. 3월 1일 ActiveX Patch 적용 후, JS 로 수정한 임베딩 컨트롤이 여전히 비활성화 되는 문제 [2]
... 181  182  183  184  185  186  187  188  189  190  191  [192]  193  194  195  ...