Microsoft MVP성태의 닷넷 이야기
VC++: 154. C/C++ 언어의 문자열 Literal에 인덱스 적용하는 구문 [링크 복사], [링크+제목 복사],
조회: 14651
글쓴 사람
정성태 (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]

... 76  77  78  79  80  81  82  [83]  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11894정성태5/10/201924459VS.NET IDE: 135. Visual Studio - ML.NET Model Builder 소개 [5]
11893정성태5/10/201920550오류 유형: 535. C# 6.0 이상의 문법을 컴파일 시 오류가 발생한다면?
11892정성태5/10/201920456웹: 38. HTTP Cookie의 expires 시간 형식(RFC7231)
11891정성태5/9/201923595.NET Framework: 831. (번역글) .NET Internals Cookbook Part 12 - Memory structure, attributes, handles
11890정성태5/8/201919222개발 환경 구성: 439. "Visual Studio Enterprise is required to execute the test." 메시지와 관련된 코드 기록
11889정성태5/8/201919276개발 환경 구성: 438. mstest, QTAgent의 로그 파일 설정 방법
11888정성태5/8/201937166.NET Framework: 830. C# - 비동기 호출을 취소하는 CancellationToken의 간단한 예제 코드 [1]파일 다운로드1
11887정성태5/8/201923046.NET Framework: 829. C# - yield 문을 사용할 수 있는 메서드의 조건
11886정성태5/7/201920095오류 유형: 534. mstest.exe 실행 시 "Visual Studio Enterprise is required to execute the test." 오류 [2]
11885정성태5/7/201917572오류 유형: 533. mstest.exe 실행 시 "File extension specified '.loadtest' is not a valid test extension." 오류 발생
11884정성태5/5/201922483.NET Framework: 828. C# DLL에서 Win32 C/C++처럼 dllexport 함수를 제공하는 방법 - 두 번째 이야기
11883정성태5/3/201927489.NET Framework: 827. C# - 인터넷 시간 서버로부터 받은 시간을 윈도우에 적용하는 방법파일 다운로드1
11882정성태5/2/201923939.NET Framework: 826. (번역글) .NET Internals Cookbook Part 11 - Various C# riddles파일 다운로드1
11881정성태4/28/201924050오류 유형: 532. .NET Core 프로젝트로 마이그레이션 시 "CS0579 Duplicate 'System.Reflection.AssemblyCompanyAttribute' attribute" 오류 발생
11880정성태4/25/201919787오류 유형: 531. 이벤트 로그 오류 - Task Scheduling Error: m->NextScheduledSPRetry 1547, m->NextScheduledEvent 1547
11879정성태4/24/201928718.NET Framework: 825. (번역글) .NET Internals Cookbook Part 10 - Threads, Tasks, asynchronous code and others파일 다운로드2
11878정성태4/22/201923965.NET Framework: 824. (번역글) .NET Internals Cookbook Part 9 - Finalizers, queues, card tables and other GC stuff파일 다운로드1
11877정성태4/22/201924175.NET Framework: 823. (번역글) .NET Internals Cookbook Part 8 - C# gotchas파일 다운로드1
11876정성태4/21/201922483.NET Framework: 822. (번역글) .NET Internals Cookbook Part 7 - Word tearing, locking and others파일 다운로드1
11875정성태4/21/201924288오류 유형: 530. Visual Studo에서 .NET Core 프로젝트를 열 때 "One or more errors occurred." 오류 발생
11874정성태4/20/201924318.NET Framework: 821. (번역글) .NET Internals Cookbook Part 6 - Object internals파일 다운로드1
11873정성태4/19/201922965.NET Framework: 820. (번역글) .NET Internals Cookbook Part 5 - Methods, parameters, modifiers파일 다운로드1
11872정성태4/17/201923845.NET Framework: 819. (번역글) .NET Internals Cookbook Part 4 - Type members파일 다운로드1
11871정성태4/16/201921721.NET Framework: 818. (번역글) .NET Internals Cookbook Part 3 - Initialization tricks [3]파일 다운로드1
11870정성태4/16/201920607.NET Framework: 817. Process.Start로 실행한 콘솔 프로그램의 출력 결과를 얻는 방법파일 다운로드1
11869정성태4/15/201926929.NET Framework: 816. (번역글) .NET Internals Cookbook Part 2 - GC-related things [2]파일 다운로드2
... 76  77  78  79  80  81  82  [83]  84  85  86  87  88  89  90  ...