Alternative to switch/case?

This is a discussion on Alternative to switch/case? within the C Programming forums, part of the General Programming Boards category; Hi I'm new to C and was wondering whether there is a better way to solve my problem than a ...

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    6

    Question Alternative to switch/case?

    Hi I'm new to C and was wondering whether there is a better way to solve my problem than a switch( ) case statment.

    I'm trying to decode a byte of data from an ICMP packet, because it's a byte, it can have 256 different values, with most of the values relating to a different piece of content. Currently i am using this method:

    Code:
    switch (value)
    
      {
    
      case 0:    printf("0 echo reply");
         break;
    
      case 1:    printf("1 unassigned");
         break;
    
      case 2:    printf("2 unassigned");
         break;
    
      case 3:    printf("3 destination unreachable")
         break;
    
      case 4;    printf("4 source quench")
         break;
    
    ..... and so on and so on......... until 255
    As you can imagine this method is quite time consuming, is there a better/more efficient way to do this?

    Any help would be greatly appreciated
    Thanks

  2. #2
    Rabble Rouser Slacker's Avatar
    Join Date
    Dec 2005
    Posts
    116
    Code:
    const char *content[] = {
      "echo reply",
      "unassigned",
      "unassigned",
      "destination unreachable",
      "source quench"
      ... and so on until 255
    };
    
    ...
    
    printf ( "%d %s", value, content[value] );

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Alternative to malloc
    By stellastarr in forum C Programming
    Replies: 13
    Last Post: 04-30-2007, 05:10 PM
  2. ASP.NET alternative to gallery.menalto.com ???
    By gicio in forum C# Programming
    Replies: 0
    Last Post: 05-15-2005, 12:31 PM
  3. Alternative to fstream
    By golfinguy4 in forum Windows Programming
    Replies: 3
    Last Post: 07-03-2002, 02:51 AM
  4. alternative to cin
    By Unregistered in forum C++ Programming
    Replies: 18
    Last Post: 06-25-2002, 06:14 PM
  5. ansi alternative to this?
    By Ragman in forum C Programming
    Replies: 4
    Last Post: 06-13-2002, 02:58 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21