c++에서 ~연산자에 대해서

익명 사용자의 이미지
대소고의 이미지

마지막에 출력되는 값은 ~(~a)인데 그럼 반전된 값을 다시 반전하니 비트가 몇개든 원래값인 false로 돌아와야하는거 아닌가요..? 비트개수말고도 다른게 있는거같아요

raymundo의 이미지

https://stackoverflow.com/questions/21976630/tilde-operator-returning-1-2-instead-of-0-1-respectively

여기 답글에 보면 ~ 연산자의 피연산자는 int 타입으로 프로모션 된다고 하는군요.

아마도 다음 순서로 진행된 것 같습니다만 확신은 없네요.

bool a = false; // 0
 
a = ~a;
//  a : 00000000 00000000 00000000 00000000 (프로모션된 값)
// ~a : 11111111 11111111 11111111 11111111 
//  a : 0이 아닌 값을 bool로 변환하니 1
 
a = ~a;
//  a : 00000000 00000000 00000000 00000001
// ~a : 11111111 11111111 11111111 11111110
//  a : 0이 아닌 값을 bool로 변환하니 1

좋은 하루 되세요!

익명 사용자의 이미지

ㅋㅋㅋㅋ 이런 재밌는 질문을 들고오면 답을 달 수밖에 없잖아요.
빨리 남은 일 끝내고 자야 하는데 큰일났네.

이렇게 보면 문제의 원인이 더 잘 보입니다:

#include <iostream>
using namespace std;
 
#define EVALUATE_AND_PRINT(EXPR) \
	cout << "\"" #EXPR "\" is evaluated to "; print(EXPR); cout << endl;
 
void print(int v){ cout << "(int)" << v; }
void print(bool v){ cout << "(bool)" << v; }
 
int main() {
	cout << showbase << hex << boolalpha;
 
	bool b;
	EVALUATE_AND_PRINT(b = true);
	EVALUATE_AND_PRINT(~b);
	EVALUATE_AND_PRINT(b = ~b);
	return 0;
}

실행 결과: (https://ideone.com/qBjw99)

"b = true" is evaluated to (bool)true
"~b" is evaluated to (int)0xfffffffe
"b = ~b" is evaluated to (bool)true
  1. b에 true를 대입하면 당연히 b는 (bool)true가 됩니다. (출력 첫째 줄)
  2. ~b를 계산할 때,
    1. Unary operator ~는 먼저 피연산자 b에 대해 Integral promotions을 적용합니다.
    2. Integral promotions에 의해 b(=(bool)true)는 (int)1이 됩니다.
    3. Unary operator ~는 (int)1에 대해 ones' complement를 계산하며, 결과 타입은 promoted operand의 타입, 즉 int가 됩니다.
    4. 결과값은 int 타입의 크기에 따라 다르겠습니다만, 4바이트라면 (int)0xfffffffe가 되겠죠.
    5. 따라서 ~b는 (int)0xfffffffe가 나올 겁니다. (출력 둘째 줄)
  3. b = ~b를 하면 ~b의 값 (int)0xfffffffe가 bool 타입으로 변환되어 b에 저장됩니다.
    1. 이 변환에서는 Boolean conversions 규칙이 적용됩니다.
    2. Boolean conversions에 따르면 0이 아닌 정수 값은 (bool)true가 됩니다. (출력 셋째 줄)

따라서 질문자님이 관찰하신 결과가 올바릅니다.

다만, bool이 1비트가 아니어서 생긴 문제가 아니라, Unary operator ~가 피연산자에 대해 Integral promotions을 적용해서 int로 만들고, 그 결과에 다시 Boolean conversions을 적용해서 bool로 돌아오기 때문에 생기는 문제입니다.

bool 가지고 논리 연산을 하고 싶으시면 Unary operator !를 쓰세요. 이 연산자는 피연산자를 먼저 bool 타입으로 변환한 뒤 true와 false를 뒤바꿉니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.