Skip to main content

C++ of the Day #10 - null pointer constant

Question

오늘은 오랫만에 뉴스그룹에서 하나 가져왔습니다. ((comp.lang.c++.moderated:conversion from int to int * of zero in comma operator))
int* p = (0, 0);
질문은
- 위의 코드가 컴파일이 되지 않는 이유는 무엇인가요? ((g++에서는 -pedantic 옵션을 주어야 합니다. 참고로 -pedantic 옵션은 표준에 부합되지 않는 모든 경우에 대해 에러를 발생시키고자 할때 사용됩니다.))

Answer

위의 코드는 얼핏 봐서는 아무 문제 없이 컴파일이 되어야 할 것 같습니다. 오른편의 comma operator는 왼쪽부터 오른쪽으로 수행되며 마지막으로 제일 오른쪽의 식의 결과가 리턴되는 operator이기 때문에 이 식의 리턴 값은 0 이 됩니다. 게다가 이 0 은 integral constant expression이기 때문이죠.

그럼 왜 이 문장이 컴파일이 안되는지 알아보겠습니다.

먼저 표준 문서의 4.10(1) 을 보면 null pointer constant에 대한 다음과 같은 내용이 나옵니다.
A null pointer constant is an integral constant expression (5.19) rvalue of integer type that evaluates to zero. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of pointer to object or pointer to function type. Two null pointer values of the same type shall compare equal. The conversion of a null pointer constant to a pointer to cvqualified type is a single conversion, and not the sequence of a pointer conversion followed by a qualification conversion (4.4).
제일 첫 문장을 보면 예상했듯이 null pointer constant로 사용되기 위해서는 0 으로 evaluation 되는 integral constant expression이어야 된다는 것을 알 수 있습니다. 그럼 integral constant expression에 대한 내용을 5.19 에서 찾아봅시다.
An integral constant expression can involve only literals (2.13), enumerators, const variables or static data members of integral or enumeration types initialized with constant expressions (8.5), nontype template parameters of integral or enumeration types, and sizeof expressions. Floating literals (2.13.3) can appear only if they are cast to integral or enumeration types. Only type conversions to integral or enumeration types can be used. In particular, except in sizeof expressions, functions, class objects, pointers, or references shall not be used, and assignment, increment, decrement, functioncall, or comma operators shall not be used.
첫 부분을 보면 literal들, enum 값들 등등이 integral constant expression이라고 나와 있습니다. 그런데 제일 마지막 문장을 보면 comma operator는 아니다라고 떡하니 나와 있네요.

이제 왜 문제에 나와 있는 문장이 컴파일이 되지 않는지는 알았습니다. 이유는 다시 한번 정리하자면 "null pointer constant는 0이 되는 integral constant expression이어야 하는데 comma operator는 이것이 아니기 때문"입니다.

그럼 왜 표준에서는 이렇게 정의를 해놓았을까요? Francis Glassborow의 답변 ((http://tinyurl.com/q4co7)) 에서 힌트를 얻어 보자면 컴파일러로 하여금 컴파일시에 어떤 식(comma expression)을 수행해보지 않고도 integral constant를 얻을 수 있도록 하기 위해서 인것 같습니다. 비록 이 경우에는 그 expression (comma expression)의 모든 인자가 constant이더라도 말이지요. ;-)

Comments

Popular posts from this blog

1의 개수 세기 - 해답

벌써 어제 말한 내일이 되었는데 답을 주신 분이 아무도 없어서 좀 뻘쭘하네요. :-P 그리고 어제 문제에 O(1)이라고 적었는데 엄밀히 얘기하자면 O(log 10 n)이라고 적었어야 했네요. 죄송합니다. ... 문제를 잠시 생각해보면 1~n까지의 수들 중 1의 개수를 얻기 위해서는 해당 숫자 n의 각 자리의 1의 개수가 모두 몇개나 될지를 구해서 더하면 된다는 사실을 알 수 있습니다. 예를 들어 13이라는 수를 생각해 보면 1~13까지의 수에서 1의 자리에는 1이 모두 몇개나 되는지와 10의 자리에는 모두 몇개나 되는지를 구해 이 값을 더하면 됩니다. 먼저 1의 자리를 생각해 보면 1, 11의 두 개가 있으며 10의 자리의 경우, 10, 11, 12, 13의 네 개가 있습니다. 따라서 2+4=6이라는 값을 구할 수 있습니다. 이번엔 234라는 수에서 10의 자리를 예로 들어 살펴 보겠습니다. 1~234라는 수들 중 10의 자리에 1이 들어가는 수는 10, 11, ..., 19, 110, 111, ... 119, 210, 211, ..., 219들로 모두 30개가 있음을 알 수 있습니다. 이 규칙들을 보면 해당 자리수의 1의 개수를 구하는 공식을 만들 수 있습니다. 234의 10의 자리에 해당하는 1의 개수는 ((234/100)+1)*10이 됩니다. 여기서 +1은 해당 자리수의 수가 0이 아닌 경우에만 더해집니다. 예를 들어 204라면 ((204/100)+0)*10으로 30개가 아닌 20개가 됩니다. 이런 방식으로 234의 각 자리수의 1의 개수를 구하면 1의 자리에 해당하는 1의 개수는 ((234/10)+1)*1=24개가 되고 100의 자리에 해당하는 개수는 ((234/1000)+1)*100=100이 됩니다. 이들 세 수를 모두 합하면 24+30+100=154개가 됩니다. 한가지 추가로 생각해야 할 점은 제일 큰 자리의 수가 1인 경우 위의 공식이 아닌 다른 공식이 필요하다는 점입니다. 예를 들어 123에서 100의 자리에 해당하는 1의 개수는 ((123/1...

CodeHighlighter plugin test page.

This post is for testing CodeHighlighter plugin which uses GeSHi as a fontifier engine. ((Those code blocks are acquired from Google Code Search .)) ((For more supported languages, go CodeHighlighter plugin or GeSHi homepage.)) C++ (<pre lang="cpp" lineno="1">) class nsScannerBufferList { public: /** * Buffer objects are directly followed by a data segment. The start * of the data segment is determined by increment the |this| pointer * by 1 unit. */ class Buffer : public PRCList { public: Buffer() { ++index_; } PHP (<pre lang="php" lineno="4">) for ($i = 0; $i $value = ord( $utf8_string[ $i ] ); if ( $value < 128 ) { // ASCII $unicode .= chr($value); } else { if ( count( $values ) == 0 ) { $num_octets = ( $value } $values[] = $value; Lisp (<pre lang="lisp">) ;;; Assignment (define-caller-pattern setq ((:star var fo...

Coverity Prevent - 소스 코드 검사 도구

이번에 회사에서 소스 코드 검사 도구를 하나 구입하는데 이것저것 비교해본 결과 Coverity Prevent 라는 툴이 가장 좋아 이걸로 결정했다고 하더군요. 간단히 말하자면 Lint 처럼 소스 코드에 대해 static analysis를 하는 도구입니다. 그래서 시험삼아 돌려본 결과를 보게 되었는데 그 품질이 정말 놀랍군요. 메모리 릭이나 초기화하지 않은 변수, 버퍼 오버런, null 체크등등 거의 정확하게 에러를 보고해 줍니다. 다음은 전체 코드에서 발견된 문제점들을 리스트 형태로 보여주는 화면입니다. 정말 많군요. ;-) 다음은 이중 하나의 에러를 자세히 보기 위해 선택하여 들어간 화면입니다. 소스 코드에 라인번호와 에러가 발생한 위치, 에러가 발생할 수 있는 조건들을 자세히 보여줍니다. 정말 '와우!'입니다. 각 함수와 같은 이름들을 클릭하면 그 함수로 바로 이동할 수 있습니다. 사용해보니 개인적으로는 purify 같은 runtime 검사 도구보다 더 맘에 드는군요. 사실 Lint 계열의 도구들은 한번도 사용해본 적이 없는데 다른 것들도 한번 구해다 써봐야겠습니다. 이 툴의 유일한 문제는 비싸다는 것이랍니다. :-)