Can I check a small array of bools in one go?What is the strict aliasing rule?How do Python's any and all functions work?What is the purpose of std::launder?trap representationCan I check in C(++) if an array is all 0 (or false)?Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How to append something to an array?Checking if a key exists in a JavaScript object?Loop through an array in JavaScriptHow to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?Why is processing a sorted array faster than processing an unsorted array?Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations
Levenshtein Neighbours
Land Registry Clause
Which basis does the wavefunction collapse to?
My new Acer Aspire 7 doesn't have a Legacy Boot option, what can I do to get it?
Would getting a natural 20 with a penalty still count as a critical hit?
What is "super" in superphosphate?
Do living authors still get paid royalties for their old work?
Sinc interpolation in spatial domain
Why don't modern jet engines use forced exhaust mixing?
Inset Square From a Rectangular Face
Expand def in write18
Have made several mistakes during the course of my PhD. Can't help but feel resentment. Can I get some advice about how to move forward?
Vegetarian dishes on Russian trains (European part)
Quick destruction of a helium filled airship?
Can 'in-' mean both 'in' and 'no'?
What allows us to use imaginary numbers?
Installing the original OS X version onto a Mac?
Polar contour plot in Mathematica?
Virtual destructor moves object out of rodata section
Do banks' profitability really suffer under low interest rates
Why do aircraft leave cruising altitude long before landing just to circle?
How does the illumination of the sky from the sun compare to that of the moon?
Independence of Mean and Variance of Discrete Uniform Distributions
Does git delete empty folders?
Can I check a small array of bools in one go?
What is the strict aliasing rule?How do Python's any and all functions work?What is the purpose of std::launder?trap representationCan I check in C(++) if an array is all 0 (or false)?Create ArrayList from arrayHow do I check if an array includes an object in JavaScript?How to append something to an array?Checking if a key exists in a JavaScript object?Loop through an array in JavaScriptHow to check if an object is an array?How do I remove a particular element from an array in JavaScript?For-each over an array in JavaScript?Why is processing a sorted array faster than processing an unsorted array?Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
There was a similar question here, but the user in that question seemed to have a much larger array, or vector. If I have:
bool boolArray[4];
And I want to check if all elements are false, I can check [ 0 ], [ 1 ] , [ 2 ] and [ 3 ] either separately, or I can loop through it. Since (as far as I know) false should have value 0 and anything other than 0 is true, I thought about simply doing:
if ( *(int*) boolArray)
This works, but I realize that it relies on bool being one byte and int being four bytes. If I cast to (std::uint32_t) would it be OK, or is it still a bad idea? I just happen to have 3 or 4 bools in an array and was wondering if this is safe, and if not if there is a better way to do it.
Also, in the case I end up with more than 4 bools but less than 8 can I do the same thing with a std::uint64_t or unsigned long long or something?
c++ arrays casting
add a comment |
There was a similar question here, but the user in that question seemed to have a much larger array, or vector. If I have:
bool boolArray[4];
And I want to check if all elements are false, I can check [ 0 ], [ 1 ] , [ 2 ] and [ 3 ] either separately, or I can loop through it. Since (as far as I know) false should have value 0 and anything other than 0 is true, I thought about simply doing:
if ( *(int*) boolArray)
This works, but I realize that it relies on bool being one byte and int being four bytes. If I cast to (std::uint32_t) would it be OK, or is it still a bad idea? I just happen to have 3 or 4 bools in an array and was wondering if this is safe, and if not if there is a better way to do it.
Also, in the case I end up with more than 4 bools but less than 8 can I do the same thing with a std::uint64_t or unsigned long long or something?
c++ arrays casting
2
What about using astd::bitset
?
– πάντα ῥεῖ
12 hours ago
2
@πάνταῥεῖ I haven't thought about that, I just used what was obvious to me at the time, an array. BTW, this site is getting weird. This may be a really dumb question so I welcome all downvotes, but I got a downvote literally within 5 seconds of posting it.
– Zebrafish
12 hours ago
"This may be a really dumb question so I welcome all downvotes, but I got a downvote literally within 5 seconds of posting it." Sorry, it was my DV. Reading about array or vector of bools rings my alarm bells. I retracted my DV now.
– πάντα ῥεῖ
12 hours ago
Well I'll look into std::bitset I guess. I just used an array as it was most obvious to me, I just used it for left, middle and right mouse buttons down.
– Zebrafish
12 hours ago
add a comment |
There was a similar question here, but the user in that question seemed to have a much larger array, or vector. If I have:
bool boolArray[4];
And I want to check if all elements are false, I can check [ 0 ], [ 1 ] , [ 2 ] and [ 3 ] either separately, or I can loop through it. Since (as far as I know) false should have value 0 and anything other than 0 is true, I thought about simply doing:
if ( *(int*) boolArray)
This works, but I realize that it relies on bool being one byte and int being four bytes. If I cast to (std::uint32_t) would it be OK, or is it still a bad idea? I just happen to have 3 or 4 bools in an array and was wondering if this is safe, and if not if there is a better way to do it.
Also, in the case I end up with more than 4 bools but less than 8 can I do the same thing with a std::uint64_t or unsigned long long or something?
c++ arrays casting
There was a similar question here, but the user in that question seemed to have a much larger array, or vector. If I have:
bool boolArray[4];
And I want to check if all elements are false, I can check [ 0 ], [ 1 ] , [ 2 ] and [ 3 ] either separately, or I can loop through it. Since (as far as I know) false should have value 0 and anything other than 0 is true, I thought about simply doing:
if ( *(int*) boolArray)
This works, but I realize that it relies on bool being one byte and int being four bytes. If I cast to (std::uint32_t) would it be OK, or is it still a bad idea? I just happen to have 3 or 4 bools in an array and was wondering if this is safe, and if not if there is a better way to do it.
Also, in the case I end up with more than 4 bools but less than 8 can I do the same thing with a std::uint64_t or unsigned long long or something?
c++ arrays casting
c++ arrays casting
edited 12 hours ago
Zebrafish
asked 12 hours ago
ZebrafishZebrafish
4,0731 gold badge15 silver badges42 bronze badges
4,0731 gold badge15 silver badges42 bronze badges
2
What about using astd::bitset
?
– πάντα ῥεῖ
12 hours ago
2
@πάνταῥεῖ I haven't thought about that, I just used what was obvious to me at the time, an array. BTW, this site is getting weird. This may be a really dumb question so I welcome all downvotes, but I got a downvote literally within 5 seconds of posting it.
– Zebrafish
12 hours ago
"This may be a really dumb question so I welcome all downvotes, but I got a downvote literally within 5 seconds of posting it." Sorry, it was my DV. Reading about array or vector of bools rings my alarm bells. I retracted my DV now.
– πάντα ῥεῖ
12 hours ago
Well I'll look into std::bitset I guess. I just used an array as it was most obvious to me, I just used it for left, middle and right mouse buttons down.
– Zebrafish
12 hours ago
add a comment |
2
What about using astd::bitset
?
– πάντα ῥεῖ
12 hours ago
2
@πάνταῥεῖ I haven't thought about that, I just used what was obvious to me at the time, an array. BTW, this site is getting weird. This may be a really dumb question so I welcome all downvotes, but I got a downvote literally within 5 seconds of posting it.
– Zebrafish
12 hours ago
"This may be a really dumb question so I welcome all downvotes, but I got a downvote literally within 5 seconds of posting it." Sorry, it was my DV. Reading about array or vector of bools rings my alarm bells. I retracted my DV now.
– πάντα ῥεῖ
12 hours ago
Well I'll look into std::bitset I guess. I just used an array as it was most obvious to me, I just used it for left, middle and right mouse buttons down.
– Zebrafish
12 hours ago
2
2
What about using a
std::bitset
?– πάντα ῥεῖ
12 hours ago
What about using a
std::bitset
?– πάντα ῥεῖ
12 hours ago
2
2
@πάνταῥεῖ I haven't thought about that, I just used what was obvious to me at the time, an array. BTW, this site is getting weird. This may be a really dumb question so I welcome all downvotes, but I got a downvote literally within 5 seconds of posting it.
– Zebrafish
12 hours ago
@πάνταῥεῖ I haven't thought about that, I just used what was obvious to me at the time, an array. BTW, this site is getting weird. This may be a really dumb question so I welcome all downvotes, but I got a downvote literally within 5 seconds of posting it.
– Zebrafish
12 hours ago
"This may be a really dumb question so I welcome all downvotes, but I got a downvote literally within 5 seconds of posting it." Sorry, it was my DV. Reading about array or vector of bools rings my alarm bells. I retracted my DV now.
– πάντα ῥεῖ
12 hours ago
"This may be a really dumb question so I welcome all downvotes, but I got a downvote literally within 5 seconds of posting it." Sorry, it was my DV. Reading about array or vector of bools rings my alarm bells. I retracted my DV now.
– πάντα ῥεῖ
12 hours ago
Well I'll look into std::bitset I guess. I just used an array as it was most obvious to me, I just used it for left, middle and right mouse buttons down.
– Zebrafish
12 hours ago
Well I'll look into std::bitset I guess. I just used an array as it was most obvious to me, I just used it for left, middle and right mouse buttons down.
– Zebrafish
12 hours ago
add a comment |
5 Answers
5
active
oldest
votes
As πάντα ῥεῖ noticed in comments, std::bitset
is probably the best way to deal with that in UB-free manner.
std::bitset<4> boolArray ;
if(boolArray.any())
//do the thing
If you want to stick to arrays, you could use std::any_of
, but this requires (possibly peculiar to the readers) usage of functor which just returns its argument:
bool boolArray[4];
if(std::any_of(std::begin(boolArray), std::end(boolArray), [](bool b)return b;)
//do the thing
Type-punning 4 bool
s to int
might be a bad idea - you cannot be sure of the size of each of the types. It probably will work on most architectures, but std::bitset
is guaranteed to work everywhere, under any circumstances.
1
Last I spoke to bitset he was nothing but mean to me. I wouldn't call him a friend.
– Sombrero Chicken
12 hours ago
@SombreroChicken Friends are mean sometimes, but I'm sure he meant well
– Yksisarvinen
12 hours ago
11
@SombreroChicken - Don't take it personally, he's a bit off.
– StoryTeller
12 hours ago
"Order positions are counted from the rightmost bit", so that if I do std::bitset<4> foo; foo[1] = true; the output from cout is 0010. I know it doesn't matter, but do you know why the first index is the last bit?
– Zebrafish
12 hours ago
@Zebrafish Probably to make it more resembling clasical bit operations.myBitset[3]
is equivalent tomyInt & (1 << 3)
. This way you can transfer simply from the old C way of masking bits to C++std::bitset
more easily. I guess storing array of bools wasn't its primary purpose ;)
– Yksisarvinen
12 hours ago
add a comment |
You can use std::bitset<N>::any
:
Any returns true
if any of the bits are set to true
, otherwise false
.
#include <iostream>
#include <bitset>
int main ()
std::bitset<4> foo;
// modify foo here
if (foo.any())
std::cout << foo << " has " << foo.count() << " bits set.n";
else
std::cout << foo << " has no bits set.n";
return 0;
Live
If you want to return true
if all or none of the bits set to on, you can use std::bitset<N>::all
or std::bitset<N>::none
respectively.
add a comment |
The standard library has what you need in the form of the std::all_of, std::any_of, std::none_of algorithms.
add a comment |
...And for the obligatory "roll your own" answer, we can provide a simple "or"-like function for any array bool[N]
, like so:
template<size_t N>
constexpr bool or_all(const bool (&bs)[N])
for (bool b : bs)
if (b) return b;
return false;
Or more concisely,
template<size_t N>
constexpr bool or_all(const bool (&bs)[N])
for (bool b : bs) if (b) return b;
return false;
This also has the benefit of both short-circuiting like ||
, and being optimised out entirely if calculable at compile time.
Apart from that, if you want to examine the original idea of type-punning bool[N]
to some other type to simplify observation, I would very much recommend that you don't do that view it as char[N2]
instead, where N2 == (sizeof(bool) * N)
. This would allow you to provide a simple representation viewer that can automatically scale to the viewed object's actual size, allow iteration over its individual bytes, and allow you to more easily determine whether the representation matches specific values (such as, e.g., zero or non-zero). I'm not entirely sure off the top of my head whether such examination would invoke any UB, but I can say for certain that any such type's construction cannot be a viable constant-expression, due to requiring a reinterpret cast to char*
or unsigned char*
or similar (either explicitly, or in std::memcpy()
), and thus couldn't as easily be optimised out.
add a comment |
Several answers have already explained good alternatives, particularly std::bitset
and std::any_of()
. I am writing separately to point out that, unless you know something we don't, it is not safe to type pun between bool
and int
in this fashion, for several reasons:
int
might not be four bytes, as multiple answers have pointed out.int
can have trap representations. That is, it is legal for certain bit patterns to cause undefined behavior when they are cast toint
. This is rare on modern architectures, but might arise on (for example) ia64, or any system with signed zeros.- Regardless of whether you have to worry about (1) or (2), your code violates the strict aliasing rule, so compilers are free to "optimize" it under the assumption that the bools and the int are entirely separate objects with non-overlapping lifetimes. For example, the compiler might decide that the code which initializes the bool array is a dead store and eliminate it, because the bools "must have" ceased to exist* at some point before you dereferenced the pointer. More complicated situations can also arise relating to register reuse and load/store reordering. All of these infelicities are expressly permitted by the C++ standard, which says the behavior is undefined when you engage in this kind of type punning.
You should use one of the alternative solutions provided by the other answers.
* It is legal to reuse the memory pointed to by boolArray
by casting it to int and storing an integer, although if you actually want to do this, you must then pass boolArray
through std::launder
if you want to read the resulting int later. Regardless, the compiler is entitled to assume that you have done this once it sees the read, even if you don't call launder.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57544478%2fcan-i-check-a-small-array-of-bools-in-one-go%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
As πάντα ῥεῖ noticed in comments, std::bitset
is probably the best way to deal with that in UB-free manner.
std::bitset<4> boolArray ;
if(boolArray.any())
//do the thing
If you want to stick to arrays, you could use std::any_of
, but this requires (possibly peculiar to the readers) usage of functor which just returns its argument:
bool boolArray[4];
if(std::any_of(std::begin(boolArray), std::end(boolArray), [](bool b)return b;)
//do the thing
Type-punning 4 bool
s to int
might be a bad idea - you cannot be sure of the size of each of the types. It probably will work on most architectures, but std::bitset
is guaranteed to work everywhere, under any circumstances.
1
Last I spoke to bitset he was nothing but mean to me. I wouldn't call him a friend.
– Sombrero Chicken
12 hours ago
@SombreroChicken Friends are mean sometimes, but I'm sure he meant well
– Yksisarvinen
12 hours ago
11
@SombreroChicken - Don't take it personally, he's a bit off.
– StoryTeller
12 hours ago
"Order positions are counted from the rightmost bit", so that if I do std::bitset<4> foo; foo[1] = true; the output from cout is 0010. I know it doesn't matter, but do you know why the first index is the last bit?
– Zebrafish
12 hours ago
@Zebrafish Probably to make it more resembling clasical bit operations.myBitset[3]
is equivalent tomyInt & (1 << 3)
. This way you can transfer simply from the old C way of masking bits to C++std::bitset
more easily. I guess storing array of bools wasn't its primary purpose ;)
– Yksisarvinen
12 hours ago
add a comment |
As πάντα ῥεῖ noticed in comments, std::bitset
is probably the best way to deal with that in UB-free manner.
std::bitset<4> boolArray ;
if(boolArray.any())
//do the thing
If you want to stick to arrays, you could use std::any_of
, but this requires (possibly peculiar to the readers) usage of functor which just returns its argument:
bool boolArray[4];
if(std::any_of(std::begin(boolArray), std::end(boolArray), [](bool b)return b;)
//do the thing
Type-punning 4 bool
s to int
might be a bad idea - you cannot be sure of the size of each of the types. It probably will work on most architectures, but std::bitset
is guaranteed to work everywhere, under any circumstances.
1
Last I spoke to bitset he was nothing but mean to me. I wouldn't call him a friend.
– Sombrero Chicken
12 hours ago
@SombreroChicken Friends are mean sometimes, but I'm sure he meant well
– Yksisarvinen
12 hours ago
11
@SombreroChicken - Don't take it personally, he's a bit off.
– StoryTeller
12 hours ago
"Order positions are counted from the rightmost bit", so that if I do std::bitset<4> foo; foo[1] = true; the output from cout is 0010. I know it doesn't matter, but do you know why the first index is the last bit?
– Zebrafish
12 hours ago
@Zebrafish Probably to make it more resembling clasical bit operations.myBitset[3]
is equivalent tomyInt & (1 << 3)
. This way you can transfer simply from the old C way of masking bits to C++std::bitset
more easily. I guess storing array of bools wasn't its primary purpose ;)
– Yksisarvinen
12 hours ago
add a comment |
As πάντα ῥεῖ noticed in comments, std::bitset
is probably the best way to deal with that in UB-free manner.
std::bitset<4> boolArray ;
if(boolArray.any())
//do the thing
If you want to stick to arrays, you could use std::any_of
, but this requires (possibly peculiar to the readers) usage of functor which just returns its argument:
bool boolArray[4];
if(std::any_of(std::begin(boolArray), std::end(boolArray), [](bool b)return b;)
//do the thing
Type-punning 4 bool
s to int
might be a bad idea - you cannot be sure of the size of each of the types. It probably will work on most architectures, but std::bitset
is guaranteed to work everywhere, under any circumstances.
As πάντα ῥεῖ noticed in comments, std::bitset
is probably the best way to deal with that in UB-free manner.
std::bitset<4> boolArray ;
if(boolArray.any())
//do the thing
If you want to stick to arrays, you could use std::any_of
, but this requires (possibly peculiar to the readers) usage of functor which just returns its argument:
bool boolArray[4];
if(std::any_of(std::begin(boolArray), std::end(boolArray), [](bool b)return b;)
//do the thing
Type-punning 4 bool
s to int
might be a bad idea - you cannot be sure of the size of each of the types. It probably will work on most architectures, but std::bitset
is guaranteed to work everywhere, under any circumstances.
edited 12 hours ago
answered 12 hours ago
YksisarvinenYksisarvinen
3,0721 gold badge7 silver badges22 bronze badges
3,0721 gold badge7 silver badges22 bronze badges
1
Last I spoke to bitset he was nothing but mean to me. I wouldn't call him a friend.
– Sombrero Chicken
12 hours ago
@SombreroChicken Friends are mean sometimes, but I'm sure he meant well
– Yksisarvinen
12 hours ago
11
@SombreroChicken - Don't take it personally, he's a bit off.
– StoryTeller
12 hours ago
"Order positions are counted from the rightmost bit", so that if I do std::bitset<4> foo; foo[1] = true; the output from cout is 0010. I know it doesn't matter, but do you know why the first index is the last bit?
– Zebrafish
12 hours ago
@Zebrafish Probably to make it more resembling clasical bit operations.myBitset[3]
is equivalent tomyInt & (1 << 3)
. This way you can transfer simply from the old C way of masking bits to C++std::bitset
more easily. I guess storing array of bools wasn't its primary purpose ;)
– Yksisarvinen
12 hours ago
add a comment |
1
Last I spoke to bitset he was nothing but mean to me. I wouldn't call him a friend.
– Sombrero Chicken
12 hours ago
@SombreroChicken Friends are mean sometimes, but I'm sure he meant well
– Yksisarvinen
12 hours ago
11
@SombreroChicken - Don't take it personally, he's a bit off.
– StoryTeller
12 hours ago
"Order positions are counted from the rightmost bit", so that if I do std::bitset<4> foo; foo[1] = true; the output from cout is 0010. I know it doesn't matter, but do you know why the first index is the last bit?
– Zebrafish
12 hours ago
@Zebrafish Probably to make it more resembling clasical bit operations.myBitset[3]
is equivalent tomyInt & (1 << 3)
. This way you can transfer simply from the old C way of masking bits to C++std::bitset
more easily. I guess storing array of bools wasn't its primary purpose ;)
– Yksisarvinen
12 hours ago
1
1
Last I spoke to bitset he was nothing but mean to me. I wouldn't call him a friend.
– Sombrero Chicken
12 hours ago
Last I spoke to bitset he was nothing but mean to me. I wouldn't call him a friend.
– Sombrero Chicken
12 hours ago
@SombreroChicken Friends are mean sometimes, but I'm sure he meant well
– Yksisarvinen
12 hours ago
@SombreroChicken Friends are mean sometimes, but I'm sure he meant well
– Yksisarvinen
12 hours ago
11
11
@SombreroChicken - Don't take it personally, he's a bit off.
– StoryTeller
12 hours ago
@SombreroChicken - Don't take it personally, he's a bit off.
– StoryTeller
12 hours ago
"Order positions are counted from the rightmost bit", so that if I do std::bitset<4> foo; foo[1] = true; the output from cout is 0010. I know it doesn't matter, but do you know why the first index is the last bit?
– Zebrafish
12 hours ago
"Order positions are counted from the rightmost bit", so that if I do std::bitset<4> foo; foo[1] = true; the output from cout is 0010. I know it doesn't matter, but do you know why the first index is the last bit?
– Zebrafish
12 hours ago
@Zebrafish Probably to make it more resembling clasical bit operations.
myBitset[3]
is equivalent to myInt & (1 << 3)
. This way you can transfer simply from the old C way of masking bits to C++ std::bitset
more easily. I guess storing array of bools wasn't its primary purpose ;)– Yksisarvinen
12 hours ago
@Zebrafish Probably to make it more resembling clasical bit operations.
myBitset[3]
is equivalent to myInt & (1 << 3)
. This way you can transfer simply from the old C way of masking bits to C++ std::bitset
more easily. I guess storing array of bools wasn't its primary purpose ;)– Yksisarvinen
12 hours ago
add a comment |
You can use std::bitset<N>::any
:
Any returns true
if any of the bits are set to true
, otherwise false
.
#include <iostream>
#include <bitset>
int main ()
std::bitset<4> foo;
// modify foo here
if (foo.any())
std::cout << foo << " has " << foo.count() << " bits set.n";
else
std::cout << foo << " has no bits set.n";
return 0;
Live
If you want to return true
if all or none of the bits set to on, you can use std::bitset<N>::all
or std::bitset<N>::none
respectively.
add a comment |
You can use std::bitset<N>::any
:
Any returns true
if any of the bits are set to true
, otherwise false
.
#include <iostream>
#include <bitset>
int main ()
std::bitset<4> foo;
// modify foo here
if (foo.any())
std::cout << foo << " has " << foo.count() << " bits set.n";
else
std::cout << foo << " has no bits set.n";
return 0;
Live
If you want to return true
if all or none of the bits set to on, you can use std::bitset<N>::all
or std::bitset<N>::none
respectively.
add a comment |
You can use std::bitset<N>::any
:
Any returns true
if any of the bits are set to true
, otherwise false
.
#include <iostream>
#include <bitset>
int main ()
std::bitset<4> foo;
// modify foo here
if (foo.any())
std::cout << foo << " has " << foo.count() << " bits set.n";
else
std::cout << foo << " has no bits set.n";
return 0;
Live
If you want to return true
if all or none of the bits set to on, you can use std::bitset<N>::all
or std::bitset<N>::none
respectively.
You can use std::bitset<N>::any
:
Any returns true
if any of the bits are set to true
, otherwise false
.
#include <iostream>
#include <bitset>
int main ()
std::bitset<4> foo;
// modify foo here
if (foo.any())
std::cout << foo << " has " << foo.count() << " bits set.n";
else
std::cout << foo << " has no bits set.n";
return 0;
Live
If you want to return true
if all or none of the bits set to on, you can use std::bitset<N>::all
or std::bitset<N>::none
respectively.
edited 12 hours ago
answered 12 hours ago
OblivionOblivion
1,7664 silver badges20 bronze badges
1,7664 silver badges20 bronze badges
add a comment |
add a comment |
The standard library has what you need in the form of the std::all_of, std::any_of, std::none_of algorithms.
add a comment |
The standard library has what you need in the form of the std::all_of, std::any_of, std::none_of algorithms.
add a comment |
The standard library has what you need in the form of the std::all_of, std::any_of, std::none_of algorithms.
The standard library has what you need in the form of the std::all_of, std::any_of, std::none_of algorithms.
answered 12 hours ago
Jesper JuhlJesper Juhl
21.1k3 gold badges29 silver badges53 bronze badges
21.1k3 gold badges29 silver badges53 bronze badges
add a comment |
add a comment |
...And for the obligatory "roll your own" answer, we can provide a simple "or"-like function for any array bool[N]
, like so:
template<size_t N>
constexpr bool or_all(const bool (&bs)[N])
for (bool b : bs)
if (b) return b;
return false;
Or more concisely,
template<size_t N>
constexpr bool or_all(const bool (&bs)[N])
for (bool b : bs) if (b) return b;
return false;
This also has the benefit of both short-circuiting like ||
, and being optimised out entirely if calculable at compile time.
Apart from that, if you want to examine the original idea of type-punning bool[N]
to some other type to simplify observation, I would very much recommend that you don't do that view it as char[N2]
instead, where N2 == (sizeof(bool) * N)
. This would allow you to provide a simple representation viewer that can automatically scale to the viewed object's actual size, allow iteration over its individual bytes, and allow you to more easily determine whether the representation matches specific values (such as, e.g., zero or non-zero). I'm not entirely sure off the top of my head whether such examination would invoke any UB, but I can say for certain that any such type's construction cannot be a viable constant-expression, due to requiring a reinterpret cast to char*
or unsigned char*
or similar (either explicitly, or in std::memcpy()
), and thus couldn't as easily be optimised out.
add a comment |
...And for the obligatory "roll your own" answer, we can provide a simple "or"-like function for any array bool[N]
, like so:
template<size_t N>
constexpr bool or_all(const bool (&bs)[N])
for (bool b : bs)
if (b) return b;
return false;
Or more concisely,
template<size_t N>
constexpr bool or_all(const bool (&bs)[N])
for (bool b : bs) if (b) return b;
return false;
This also has the benefit of both short-circuiting like ||
, and being optimised out entirely if calculable at compile time.
Apart from that, if you want to examine the original idea of type-punning bool[N]
to some other type to simplify observation, I would very much recommend that you don't do that view it as char[N2]
instead, where N2 == (sizeof(bool) * N)
. This would allow you to provide a simple representation viewer that can automatically scale to the viewed object's actual size, allow iteration over its individual bytes, and allow you to more easily determine whether the representation matches specific values (such as, e.g., zero or non-zero). I'm not entirely sure off the top of my head whether such examination would invoke any UB, but I can say for certain that any such type's construction cannot be a viable constant-expression, due to requiring a reinterpret cast to char*
or unsigned char*
or similar (either explicitly, or in std::memcpy()
), and thus couldn't as easily be optimised out.
add a comment |
...And for the obligatory "roll your own" answer, we can provide a simple "or"-like function for any array bool[N]
, like so:
template<size_t N>
constexpr bool or_all(const bool (&bs)[N])
for (bool b : bs)
if (b) return b;
return false;
Or more concisely,
template<size_t N>
constexpr bool or_all(const bool (&bs)[N])
for (bool b : bs) if (b) return b;
return false;
This also has the benefit of both short-circuiting like ||
, and being optimised out entirely if calculable at compile time.
Apart from that, if you want to examine the original idea of type-punning bool[N]
to some other type to simplify observation, I would very much recommend that you don't do that view it as char[N2]
instead, where N2 == (sizeof(bool) * N)
. This would allow you to provide a simple representation viewer that can automatically scale to the viewed object's actual size, allow iteration over its individual bytes, and allow you to more easily determine whether the representation matches specific values (such as, e.g., zero or non-zero). I'm not entirely sure off the top of my head whether such examination would invoke any UB, but I can say for certain that any such type's construction cannot be a viable constant-expression, due to requiring a reinterpret cast to char*
or unsigned char*
or similar (either explicitly, or in std::memcpy()
), and thus couldn't as easily be optimised out.
...And for the obligatory "roll your own" answer, we can provide a simple "or"-like function for any array bool[N]
, like so:
template<size_t N>
constexpr bool or_all(const bool (&bs)[N])
for (bool b : bs)
if (b) return b;
return false;
Or more concisely,
template<size_t N>
constexpr bool or_all(const bool (&bs)[N])
for (bool b : bs) if (b) return b;
return false;
This also has the benefit of both short-circuiting like ||
, and being optimised out entirely if calculable at compile time.
Apart from that, if you want to examine the original idea of type-punning bool[N]
to some other type to simplify observation, I would very much recommend that you don't do that view it as char[N2]
instead, where N2 == (sizeof(bool) * N)
. This would allow you to provide a simple representation viewer that can automatically scale to the viewed object's actual size, allow iteration over its individual bytes, and allow you to more easily determine whether the representation matches specific values (such as, e.g., zero or non-zero). I'm not entirely sure off the top of my head whether such examination would invoke any UB, but I can say for certain that any such type's construction cannot be a viable constant-expression, due to requiring a reinterpret cast to char*
or unsigned char*
or similar (either explicitly, or in std::memcpy()
), and thus couldn't as easily be optimised out.
answered 4 hours ago
Justin TimeJustin Time
3,17916 silver badges32 bronze badges
3,17916 silver badges32 bronze badges
add a comment |
add a comment |
Several answers have already explained good alternatives, particularly std::bitset
and std::any_of()
. I am writing separately to point out that, unless you know something we don't, it is not safe to type pun between bool
and int
in this fashion, for several reasons:
int
might not be four bytes, as multiple answers have pointed out.int
can have trap representations. That is, it is legal for certain bit patterns to cause undefined behavior when they are cast toint
. This is rare on modern architectures, but might arise on (for example) ia64, or any system with signed zeros.- Regardless of whether you have to worry about (1) or (2), your code violates the strict aliasing rule, so compilers are free to "optimize" it under the assumption that the bools and the int are entirely separate objects with non-overlapping lifetimes. For example, the compiler might decide that the code which initializes the bool array is a dead store and eliminate it, because the bools "must have" ceased to exist* at some point before you dereferenced the pointer. More complicated situations can also arise relating to register reuse and load/store reordering. All of these infelicities are expressly permitted by the C++ standard, which says the behavior is undefined when you engage in this kind of type punning.
You should use one of the alternative solutions provided by the other answers.
* It is legal to reuse the memory pointed to by boolArray
by casting it to int and storing an integer, although if you actually want to do this, you must then pass boolArray
through std::launder
if you want to read the resulting int later. Regardless, the compiler is entitled to assume that you have done this once it sees the read, even if you don't call launder.
add a comment |
Several answers have already explained good alternatives, particularly std::bitset
and std::any_of()
. I am writing separately to point out that, unless you know something we don't, it is not safe to type pun between bool
and int
in this fashion, for several reasons:
int
might not be four bytes, as multiple answers have pointed out.int
can have trap representations. That is, it is legal for certain bit patterns to cause undefined behavior when they are cast toint
. This is rare on modern architectures, but might arise on (for example) ia64, or any system with signed zeros.- Regardless of whether you have to worry about (1) or (2), your code violates the strict aliasing rule, so compilers are free to "optimize" it under the assumption that the bools and the int are entirely separate objects with non-overlapping lifetimes. For example, the compiler might decide that the code which initializes the bool array is a dead store and eliminate it, because the bools "must have" ceased to exist* at some point before you dereferenced the pointer. More complicated situations can also arise relating to register reuse and load/store reordering. All of these infelicities are expressly permitted by the C++ standard, which says the behavior is undefined when you engage in this kind of type punning.
You should use one of the alternative solutions provided by the other answers.
* It is legal to reuse the memory pointed to by boolArray
by casting it to int and storing an integer, although if you actually want to do this, you must then pass boolArray
through std::launder
if you want to read the resulting int later. Regardless, the compiler is entitled to assume that you have done this once it sees the read, even if you don't call launder.
add a comment |
Several answers have already explained good alternatives, particularly std::bitset
and std::any_of()
. I am writing separately to point out that, unless you know something we don't, it is not safe to type pun between bool
and int
in this fashion, for several reasons:
int
might not be four bytes, as multiple answers have pointed out.int
can have trap representations. That is, it is legal for certain bit patterns to cause undefined behavior when they are cast toint
. This is rare on modern architectures, but might arise on (for example) ia64, or any system with signed zeros.- Regardless of whether you have to worry about (1) or (2), your code violates the strict aliasing rule, so compilers are free to "optimize" it under the assumption that the bools and the int are entirely separate objects with non-overlapping lifetimes. For example, the compiler might decide that the code which initializes the bool array is a dead store and eliminate it, because the bools "must have" ceased to exist* at some point before you dereferenced the pointer. More complicated situations can also arise relating to register reuse and load/store reordering. All of these infelicities are expressly permitted by the C++ standard, which says the behavior is undefined when you engage in this kind of type punning.
You should use one of the alternative solutions provided by the other answers.
* It is legal to reuse the memory pointed to by boolArray
by casting it to int and storing an integer, although if you actually want to do this, you must then pass boolArray
through std::launder
if you want to read the resulting int later. Regardless, the compiler is entitled to assume that you have done this once it sees the read, even if you don't call launder.
Several answers have already explained good alternatives, particularly std::bitset
and std::any_of()
. I am writing separately to point out that, unless you know something we don't, it is not safe to type pun between bool
and int
in this fashion, for several reasons:
int
might not be four bytes, as multiple answers have pointed out.int
can have trap representations. That is, it is legal for certain bit patterns to cause undefined behavior when they are cast toint
. This is rare on modern architectures, but might arise on (for example) ia64, or any system with signed zeros.- Regardless of whether you have to worry about (1) or (2), your code violates the strict aliasing rule, so compilers are free to "optimize" it under the assumption that the bools and the int are entirely separate objects with non-overlapping lifetimes. For example, the compiler might decide that the code which initializes the bool array is a dead store and eliminate it, because the bools "must have" ceased to exist* at some point before you dereferenced the pointer. More complicated situations can also arise relating to register reuse and load/store reordering. All of these infelicities are expressly permitted by the C++ standard, which says the behavior is undefined when you engage in this kind of type punning.
You should use one of the alternative solutions provided by the other answers.
* It is legal to reuse the memory pointed to by boolArray
by casting it to int and storing an integer, although if you actually want to do this, you must then pass boolArray
through std::launder
if you want to read the resulting int later. Regardless, the compiler is entitled to assume that you have done this once it sees the read, even if you don't call launder.
edited 3 hours ago
answered 3 hours ago
KevinKevin
20.2k5 gold badges38 silver badges62 bronze badges
20.2k5 gold badges38 silver badges62 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f57544478%2fcan-i-check-a-small-array-of-bools-in-one-go%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
What about using a
std::bitset
?– πάντα ῥεῖ
12 hours ago
2
@πάνταῥεῖ I haven't thought about that, I just used what was obvious to me at the time, an array. BTW, this site is getting weird. This may be a really dumb question so I welcome all downvotes, but I got a downvote literally within 5 seconds of posting it.
– Zebrafish
12 hours ago
"This may be a really dumb question so I welcome all downvotes, but I got a downvote literally within 5 seconds of posting it." Sorry, it was my DV. Reading about array or vector of bools rings my alarm bells. I retracted my DV now.
– πάντα ῥεῖ
12 hours ago
Well I'll look into std::bitset I guess. I just used an array as it was most obvious to me, I just used it for left, middle and right mouse buttons down.
– Zebrafish
12 hours ago