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;








9















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?










share|improve this question





















  • 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

















9















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?










share|improve this question





















  • 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













9












9








9


1






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?










share|improve this question
















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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












  • 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







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












5 Answers
5






active

oldest

votes


















9














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






share|improve this answer






















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



















3














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.






share|improve this answer


































    2














    The standard library has what you need in the form of the std::all_of, std::any_of, std::none_of algorithms.






    share|improve this answer
































      0














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






      share|improve this answer
































        0














        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:




        1. int might not be four bytes, as multiple answers have pointed out.


        2. int can have trap representations. That is, it is legal for certain bit patterns to cause undefined behavior when they are cast to int. This is rare on modern architectures, but might arise on (for example) ia64, or any system with signed zeros.

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






        share|improve this answer





























          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
          );



          );













          draft saved

          draft discarded


















          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









          9














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






          share|improve this answer






















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
















          9














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






          share|improve this answer






















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














          9












          9








          9







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






          share|improve this answer















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







          share|improve this answer














          share|improve this answer



          share|improve this answer








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













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








          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














          3














          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.






          share|improve this answer































            3














            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.






            share|improve this answer





























              3












              3








              3







              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.






              share|improve this answer















              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.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited 12 hours ago

























              answered 12 hours ago









              OblivionOblivion

              1,7664 silver badges20 bronze badges




              1,7664 silver badges20 bronze badges
























                  2














                  The standard library has what you need in the form of the std::all_of, std::any_of, std::none_of algorithms.






                  share|improve this answer





























                    2














                    The standard library has what you need in the form of the std::all_of, std::any_of, std::none_of algorithms.






                    share|improve this answer



























                      2












                      2








                      2







                      The standard library has what you need in the form of the std::all_of, std::any_of, std::none_of algorithms.






                      share|improve this answer













                      The standard library has what you need in the form of the std::all_of, std::any_of, std::none_of algorithms.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 12 hours ago









                      Jesper JuhlJesper Juhl

                      21.1k3 gold badges29 silver badges53 bronze badges




                      21.1k3 gold badges29 silver badges53 bronze badges
























                          0














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






                          share|improve this answer





























                            0














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






                            share|improve this answer



























                              0












                              0








                              0







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






                              share|improve this answer













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







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered 4 hours ago









                              Justin TimeJustin Time

                              3,17916 silver badges32 bronze badges




                              3,17916 silver badges32 bronze badges
























                                  0














                                  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:




                                  1. int might not be four bytes, as multiple answers have pointed out.


                                  2. int can have trap representations. That is, it is legal for certain bit patterns to cause undefined behavior when they are cast to int. This is rare on modern architectures, but might arise on (for example) ia64, or any system with signed zeros.

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






                                  share|improve this answer































                                    0














                                    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:




                                    1. int might not be four bytes, as multiple answers have pointed out.


                                    2. int can have trap representations. That is, it is legal for certain bit patterns to cause undefined behavior when they are cast to int. This is rare on modern architectures, but might arise on (for example) ia64, or any system with signed zeros.

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






                                    share|improve this answer





























                                      0












                                      0








                                      0







                                      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:




                                      1. int might not be four bytes, as multiple answers have pointed out.


                                      2. int can have trap representations. That is, it is legal for certain bit patterns to cause undefined behavior when they are cast to int. This is rare on modern architectures, but might arise on (for example) ia64, or any system with signed zeros.

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






                                      share|improve this answer















                                      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:




                                      1. int might not be four bytes, as multiple answers have pointed out.


                                      2. int can have trap representations. That is, it is legal for certain bit patterns to cause undefined behavior when they are cast to int. This is rare on modern architectures, but might arise on (for example) ia64, or any system with signed zeros.

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







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      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






























                                          draft saved

                                          draft discarded
















































                                          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.




                                          draft saved


                                          draft discarded














                                          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





















































                                          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







                                          Popular posts from this blog

                                          Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                                          Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                                          Ласкавець круглолистий Зміст Опис | Поширення | Галерея | Примітки | Посилання | Навігаційне меню58171138361-22960890446Bupleurum rotundifoliumEuro+Med PlantbasePlants of the World Online — Kew ScienceGermplasm Resources Information Network (GRIN)Ласкавецькн. VI : Літери Ком — Левиправивши або дописавши її