CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 2 of 3 FirstFirst 123 LastLast
Results 16 to 30 of 35

Thread: switch case or if else ?

  1. #16
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,486

    Re: switch case or if else ?

    Consider:

    Code:
    #include <iostream>
    #include <iomanip>
    
    using namespace std;
    using uint16 = unsigned __int16;
    
    union Bits {
    	uint16 num;
    
    	struct {
    		uint16 bit0 : 1;
    		uint16 bit1 : 1;
    		uint16 bit2 : 1;
    		uint16 bit3 : 1;
    		uint16 bit4 : 1;
    		uint16 bit5 : 1;
    		uint16 bit6 : 1;
    		uint16 bit7 : 1;
    		uint16 bit8 : 1;
    		uint16 bit9 : 1;
    		uint16 bit10 : 1;
    		uint16 bit11 : 1;
    		uint16 bit12 : 1;
    		uint16 bit13 : 1;
    		uint16 bit14 : 1;
    		uint16 bit15 : 1;
    	} b;
    };
    
    void bits(Bits b1) {
    	cout << setw(1);
    	cout << b1.b.bit0 << b1.b.bit1 << b1.b.bit2 << b1.b.bit3 << b1.b.bit4 << b1.b.bit5 << b1.b.bit6 << b1.b.bit7 << b1.b.bit8 << b1.b.bit9;
    	cout << b1.b.bit10 << b1.b.bit11 << b1.b.bit12 << b1.b.bit13 << b1.b.bit14 << b1.b.bit15 << endl;
    }
    
    int main() {
    
    	Bits t1;
    
    	t1.num = 0x04;
    
    	cout << "original:         " << hex << "0x" << setw(4) << setfill('0') << t1.num << "  ";
    	bits(t1);
    
    	Bits t2;
    
    	t2.num = t1.num >> 1;
    
    	cout << "right shift by 1: " << hex << "0x" << setw(4) << setfill('0') << t2.num << "  ";
    	bits(t2);
    
    	Bits t3;
    
    	t3.num = t1.num << 1;
    
    	cout << "left shift by 1:  " << hex << "0x" << setw(4) << setfill('0') << t3.num << "  ";
    	bits(t3);
    }
    which for Windows with little endian displays:

    Code:
    original:         0x0004  0010000000000000
    right shift by 1: 0x0002  0100000000000000
    left shift by 1:  0x0008  0001000000000000
    The right shift converts 4 to 2 as expected. However looking at the bit pattern then its actually shifted the bit pattern left as its little endian. The same for left shift. This converts 4 to 8 as expected - but its actually shifted the bit pattern right. The shift operators deal with the endiness 'behind the scenes' to give the expected results.

    As long as variables are initialised with values from within the program (eg int a = 2; ), then things work as expected. The issue comes when binary data is obtained from an external source. The endianess of this external binary data needs to be known and if its not little endian then appropriate conversion/manipulation routines need to be used.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++20 Compiler: Microsoft VS2019 (16.10.2)

  2. #17
    Join Date
    May 2015
    Posts
    450

    Re: switch case or if else ?

    Thankyou very much kaud !!! . Very helpful .

    Thanks a lot for your time to make me understand

  3. #18
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,486

    Re: switch case or if else ?

    You're welcome
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++20 Compiler: Microsoft VS2019 (16.10.2)

  4. #19
    Join Date
    May 2015
    Posts
    450

    Re: switch case or if else ?

    Now we are here discussing about this: I wanted to check if my check for LSB is correct:

    uint16 value = 0x00ff;

    if i consider the layout of value : 1111 1111 0000 0000

    The stored LSB is 0. But actual LSB is '1'
    0x00 ff : 0000 0000 1111 1111


    if do :
    uint16 value = 0xff;

    uint16 LSB = value & 1;

    I get '1' . As you said, i just need to consider the number not the underlying endianess in this case ?
    Last edited by pdk5; August 21st, 2020 at 05:49 AM.

  5. #20
    Join Date
    May 2015
    Posts
    450

    Re: switch case or if else ?

    Sorry for above post . Because of lack of sleep, i am not in good state today

  6. #21
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,486

    Re: switch case or if else ?

    The stored LSB is 0. But actual LSB is '1'
    For little-endian, the stored LSB is 1 as LSB is the left bit, not the right bit! Litle endian has the LSB at the far left (the lower memory address), whilst big-endian has the LSB at the far right (the higher memory address). For little endian, bits are numbered 0 to 15 starting from the left, not the right for internal representation. But for working with numbers etc they are used as numbered 0 to 15 starting from the right. With big endian, the internal and used representations are the same - but for little endian the internal stored representation is the reverse of that shown by cout etc.

    You only really need to bother about this if you're doing bit manipulation. Displaying a value with say cout (even using hex) doesn't show the way the number is stored internally - just its external representation. If you want to see the actual bits as stored then you need something like the bits() function.

    For little endian, the memory stored value is:
    Code:
        0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
      LSB                                            MSB

    but for big endian it is:

    Code:
       15 14 13 12 11 10  9  8  7  6  5  4  3  2  1  0
      MSB                                            LSB
    which is usually how we think of numbers when we see them.
    Last edited by 2kaud; August 21st, 2020 at 06:10 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++20 Compiler: Microsoft VS2019 (16.10.2)

  7. #22
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,486

    Re: switch case or if else ?

    PS Note that & and | works the same as shift. a & 0x01 tests the LSB of a which is either the left bit (little) or the right bit (big) depending upon endiness - but works as expected with numbers like shift does.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++20 Compiler: Microsoft VS2019 (16.10.2)

  8. #23
    Join Date
    May 2015
    Posts
    450

    Re: switch case or if else ?

    Thanks a lot kaud for all the help. your time and patience. Not sure how i can repay for the all help i received here !!! Very much appreciated.

  9. #24
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,486

    Re: switch case or if else ?

    Quote Originally Posted by pdk5 View Post
    Thanks a lot kaud for all the help. your time and patience. Not sure how i can repay for the all help i received here !!! Very much appreciated.
    Pleased to have been of help.

    For info, there is also the C++ class bitset which can help when working with bits. See https://en.cppreference.com/w/cpp/utility/bitset

    Also, there are some new stl functions which work on bits as from C++20. See https://en.cppreference.com/w/cpp/header/bit (Note that these are not yet supported in VS - coming in 16.8. The preview is available now if you want to use a preview version of VS).
    Last edited by 2kaud; August 21st, 2020 at 10:41 AM.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++20 Compiler: Microsoft VS2019 (16.10.2)

  10. #25
    Join Date
    May 2015
    Posts
    450

    Re: switch case or if else ?

    Thankyou again kaud for the links provided.

    Btw, bitset operator[] just returns one bit. It would have been helpful to specify the number of bits, ( like position and size) . Will look further. thankyou.

  11. #26
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,486

    Re: switch case or if else ?

    Quote Originally Posted by pdk5 View Post
    Thankyou again kaud for the links provided.

    Btw, bitset operator[] just returns one bit. It would have been helpful to specify the number of bits, ( like position and size) . Will look further. thankyou.
    Yes. But what would it return? [] returns type bool as 1 bit so can be only true or false. What if you had say a bitset of size 512 bits and wanted to extract say 200 bits? What would the return type be??
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++20 Compiler: Microsoft VS2019 (16.10.2)

  12. #27
    Join Date
    May 2015
    Posts
    450

    Re: switch case or if else ?

    yes, Thanks a lot kaud. .
    I was trying to see if i can use bitset for my function. i.e why i thought, if there was some member function, which can return some bits only , would have been useful

  13. #28
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,480

    Re: switch case or if else ?

    I have some general input that probably doesn't apply here.

    When I have a situation where a variety of inputs produce different outputs or actions, rather than using a hard to maintain set of if/else conditions and/or switch statements, I try to use a state table implemented via a dictionary lookup.

    The key to the dictionary is a class instance. This 'key class' instance is one entry per possible combinations of inputs (where the class itself contains properties to hold the input values). Underneath the covers the various property values form a unique hash which is the key to the dictionary.

    The value side of the dictionary contains the returned value, a class instance or an action.

    The dictionary is readonly and is initialized once during the lifetime of the program.

    To use the dictionary, the inputs are used to create a 'key class' instance and the instance is used as the dictionary key to retrieve the corresponding output vlaue, class or action.

    When the situation warrants it, I find this approach easy to debug, maintain and extend.

  14. #29
    Join Date
    Nov 2018
    Posts
    48

    Re: switch case or if else ?

    Do NOT use bit-fields to solve this problem.
    https://en.cppreference.com/w/cpp/language/bit_field

    See the notes at the end.
    "Also, on some platforms, bit fields are packed left-to-right, on others right-to-left "

    Code:
    union Bits {
    	uint16 num;
    	struct {
    		uint16 bit0 : 1;
    		uint16 bit1 : 1;
    		uint16 bit2 : 1;
    		uint16 bit3 : 1;
    		uint16 bit4 : 1;
    		uint16 bit5 : 1;
    		uint16 bit6 : 1;
    		uint16 bit7 : 1;
    		uint16 bit8 : 1;
    		uint16 bit9 : 1;
    		uint16 bit10 : 1;
    		uint16 bit11 : 1;
    		uint16 bit12 : 1;
    		uint16 bit13 : 1;
    		uint16 bit14 : 1;
    		uint16 bit15 : 1;
    	} b;
    };
    
    int main() {
    	Bits t1;
    	t1.num = 0x01;
    You might feel comfortable if you discover that t1.b.bit0 is 1 at this point.
    But there will be machines and compilers out there where it will be t1.b.bit15 that is 1.

    The only reliable way to pull apart an encoded stream from some external source is to use << >> & | ^ as appropriate.

  15. #30
    Join Date
    Feb 2017
    Posts
    606

    Re: switch case or if else ?

    Quote Originally Posted by pdk5 View Post
    So I have written following two alternatives: could u comment which is better and any other comments please ?
    You usually prefer a switch statement when you have several cases with roughly equal probability of being selected. With just two cases I would pick the if statement.

    But do you really have two cases? From what I can see this works in both cases (slightly modified from your code),
    Code:
    	usRank1elt = 1;
    	usRank2elt = ((usRank >> 1) & 0x01) + 1;
    	usRank4elt = ((usRank >> 2) & 0x03) + 1;
    	usRank8elt = ((usRank >> 4) & 0x07) + 1;
    	usRank16elt = ((usRank >> 7) & 0x0f) + 1;
    	usRank32elt = ((usRank >> 11) & 0x1f) + 1;
    To always do this also when usRank equals 1 doesn't have to be slower on average, not if usRank unequals 1 is more probable (which one perhaps can assume).

    Also by neither using if nor switch the code becomes faster. It's one selection less and the code is branch-free (which avoids costly branch prediction).
    Last edited by wolle; August 22nd, 2020 at 01:14 PM.

Page 2 of 3 FirstFirst 123 LastLast

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)