U
U
Urukhayy2014-10-27 13:52:28
C++ / C#
Urukhayy, 2014-10-27 13:52:28

How much does a Boolean variable weigh in C-like languages?

It after all 4 bytes weighs? But why 4 bytes for a true or false value? There is enough beat. Then the next question is, how can you change the value of the third bit in an ordinary variable or get its value? What features? C++.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
J
jcmvbkbc, 2014-10-27
@Urukhayy

toster.ru/answer?answer_id=396975

int v = 8;
int v3 = (v >> 3) & 1; // получил значение третьего бита (0/1)

v ^= (1 << 3); // инвертировал третий бит
v |= (1 << 3); // установил третий бит
v &= ~(1 << 3); // сбросил третий бит

D
DancingOnWater, 2014-10-27
@DancingOnWater

See bitwise operations.
Also bit fields.
This is how, for example, you can get the third bit (I wrote from my head, I am not responsible for complete correctness)

uint x = 10;
int value = (x & 0x8) >>2;

PS And 4 weighs due to the fact that all types in C dance from a 4-bit char. But no one interferes with declaring a structure 1 bit wide, but then you yourself will have to deal with alignment.

B
brutal_lobster, 2014-10-27
@brutal_lobster

Look into the c++ standard, for example: 5.3.3 Sizeof

The result of sizeof applied to any other fundamental type (3.9.1) is
implementation-defined. [ Note: in particular, sizeof(bool), sizeof(char16_t), sizeof(char32_t), and
sizeof(wchar_t) are implementation-defined

A
algol, 2014-10-27
@algol

I don't know what it's called, but...
codepad.org/zUOeXQBj

#include <stdio.h>
struct  __attribute__ ((__packed__)) A {
unsigned flag0 : 1;
unsigned flag1 : 2;
unsigned flag2 : 2;
unsigned flag3 : 3;
};
int main() {
A a = {1, 0, 2, 7};
printf("%d\n", sizeof(bool)); // 1
printf("%d\n", sizeof(A)); // 1
printf("%u %u %u %u\n", a.flag0, a.flag1, a.flag2, a.flag3); // 1 0 2 7
return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question