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

... 61  62  [63]  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12425정성태11/24/202020592VC++: 141. Visual C++ - "Treat Warnings As Errors" 옵션이 꺼져 있는데도 일부 경고가 에러 처리되는 경우
12424정성태11/24/202020698VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202020369.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/202017781.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/202016812.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/202017802오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/202017707VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202019773오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/202018690오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/202019871오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/202018945.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202022649VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202020715.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202022785.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202019079오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/202020759디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202021907.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202036874도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202021935.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202022740.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202022104.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202022808.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202019851.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202023239.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202022050VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202017925오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
... 61  62  [63]  64  65  66  67  68  69  70  71  72  73  74  75  ...