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

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...

C++ of the Day #43 - SQLite3 C++ wrapper #1

The Definitive Guide to SQLite 를 읽다가 공부 겸 해서 C++ wrapper를 만들어 보았습니다. 최대한 C++ 냄새(?)가 나도록 만들어 보았습니다. :-) ((SQLite는 복잡한 관리가 필요없이 사용가능한, 파일이나 메모리 기반의, 라이브러리로 제공되는, 약 250kb 용량의, 대부분의 SQL92문을 지원하는, open source RDB입니다.)) 이 wrapper를 사용하기 위해서는 (당연하게도!) sqlite3 와 (당연하게도?) boost 라이브러리가 필요합니다. 사용 예들을 살펴보는 것으로 설명을 대신합니다. 이번 글에서는 다음과 같은 contacts 테이블이 test.db에 존재한다고 가정합니다. CREATE TABLE contacts ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, phone TEXT NOT NULL, UNIQUE(name, phone) ); Command 먼저 test.db 파일을 사용하기 위해 다음과 같이 파일 이름을 주어 connection 객체를 생성합니다. 생성과 동시에 test.db와 연결이 이루어집니다. ((생성자외에 open() 함수를 사용할 수도 있습니다.)) sqlite3pp::connection conn("test.db"); 다음은 contacts 테이블에 정보를 추가하는 가장 간단한 방법입니다. connection 클래스에서 제공하는 execute 함수를 사용합니다. ((executef 함수를 사용하면 printf와 같은 문법을 사용하여 query문을 작성할 수 있습니다.)) conn.execute("INSERT INTO contacts (name, phone) VALUES ('user', '1234')"); 위와 동일한 작업을 parameterized query를 사용하여 할 수도 있습니다. ((step()함수가 실제 query문을 수행하는 함수입니다. ...

Textiler plugin test page

This post is for testing Textiler plugin . This plugin uses Textile engine (version 2.0.0). The sample text is come from Textile test page. (Note that the result will be vary according to your CSS options.) Supported wiki syntax Rendering result h2{color:green}. This is a title h3. This is a subhead p{color:red}. This is some text of dubious character. Isn't the use of "quotes" just lazy writing -- and theft of 'intellectual property' besides? I think the time has come to see a block quote. bq[fr]. This is a block quote. I'll admit it's not the most exciting block quote ever devised. Simple list: #{color:blue} one # two # three Multi-level list: # one ## aye ## bee ## see # two ## x ## y # three Mixed list: * Point one * Point two ## Step 1 ## Step 2 ## Step 3 * Point three ** Sub point 1 ** Sub point 2 Well, that went well. How about we insert an <a href="/" title="watch out">old-fashioned hypertext link</a>? Will the quo...