Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4615190
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T01:48:16+00:00 2026-05-22T01:48:16+00:00

I want to map struct members so I can eliminate if branches in a

  • 0

I want to map struct members so I can eliminate if branches in a loop. What is the best way or convention to implement this in C? I suppose it could be a 2 dimensional array instead…then I could map integers to the char keys?

    char chunk[32];
    int n;
    int i;
    char *ptr = config;
    while (*ptr != '\0') {
        int items_read = sscanf(ptr, "%31[^;]%n", chunk, &n);

        if(chunk[0] == 'S' && chunk[1] == 'P') {
            for(i=0;i<GLOBAL_MEAS_CUTOFF; i++) {
                theMeas[i].signal_path = atoi(&chunk[2]);
            }
        }    
        if(chunk[0] == 'T' && chunk[1] == 'L') {
            for(i=0;i<GLOBAL_MEAS_CUTOFF; i++) {
                theMeas[i].trace_length = atoi(&chunk[2]);
            }
        }    
        if(chunk[0] == 'S' && chunk[1] == 'R') {
            for(i=0;i<GLOBAL_MEAS_CUTOFF; i++) {
                theMeas[i].sample_rate = atoi(&chunk[2]);
            }
        }   

        chunk[0]='\0';
        if (items_read == 1)
            ptr += n;
        if ( *ptr != ';' ) {
            break;
        }
        ++ptr;
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T01:48:17+00:00Added an answer on May 22, 2026 at 1:48 am

    I suspect what you (ideally) want is a dictionary:

    theMeas[i]["signal_path"] = atoi(&chunk[2]);
    

    Of course, the above syntax will never happen in C, but that’s not really important here. The problem is that you would have to write all the code implementing a dictionary data type, and I suspect that’s overkill.

    So I suspect what you (really) want is a way to have names that can be used in a loop:

    foreach(signal_path, trace_length, sample_rate)
    

    And I’m here to tell you that you can do this (kind of)! The simplest way is with an enum:

    enum fields {
      signal_path,
      trace_length,
      sample_rate,
      END_fields,
      UNKNOWN_fields,
      BEGIN_fields = 0,
    };
    

    Instead of struct members, you use an array:

    int theMeas[size][END_fields];
    

    To index a “member”, use this:

    theMeas[i][signal_path];
    

    You can loop through all the “members,” you can use this:

    for(enum fields j = BEGIN_fields; j != END_fields; j++)
        theMeas[i][j];
    

    This does break down a little when you want to get character-based comparisons, but we can do a little bit:

    const char *to_str(enum fields f)
    {
    #define FIELD(x) case x: return #x
        switch(f)
          {
            FIELD(signal_path);
            FIELD(trace_length);
            FIELD(sample_rate);
            default: return "<unknown>";
          }
    #undef FIELD
    }
    
    enum fields from_str(const char *c)
    {
    #define FIELD(x) if(!strcmp(c, #x)) return x
            FIELD(signal_path);
            FIELD(trace_length);
            FIELD(sample_rate);
            default: return UNKNOWN_fields;
    #undef FIELD
    }
    
    enum fields from_abv(char *c)
    {
        for(enum fields i = BEGIN_fields; i < END_fields; i++)
          {
            char *field = field_str(i);
            if(tolower(c[0]) == field[0] && tolower(c[1]) == strchr(field, '_')[1])
                return i;
          }
        return UNKNOWN_fields;
    }
    

    Your if statements could be replaced with:

    theMeas[i][from_abv(chunk)] = atoi(&chunk[2]);
    

    Or, more safely:

    enum fields j = from_abv(chunk);
    if(j != UNKNOWN_fields) theMeas[i][j] = atoi(&chunk[2]);
    else /* erroneous user input */;
    

    Which is about as close as I can get.

    Note that I’ve deliberately used a naming scheme to facilitate the creation of macros that will automate much of this. Let’s try:

    #define member(name, ...) \
      enum name { __VA_ARGS__, \
                  M_END_##name, \
                  M_UNKNOWN_##name, \
                  M_BEGIN_##name = 0 }
    
    #define miter(name, var) \
            enum name var = M_BEGIN_##name; var != M_END_##name; var++
    
    #define msize(name) M_END_##name
    

    Usage:

    // define our fields
    member(fields, signal_path, trace_length, sample_rate);
    
    // declare object with fields
    int theMeas[N][msize(fields)];
    
    for(size_t i = 0; i < N; i++)
        // iterate over fields
        for(miter(fields, j))
            // match against fields
            if(j == from_abv(chunk))
                theMeas[i][j] = atoi(&chunk[2]);
    

    That last bit doesn’t seem so bad. It still allows you something close to struct-like access via theMeas[i][signal_path], but allows you to iterate over the “members,” and hides most of the heavy lifting behind macros.

    The to_str and from_str functions take a little more macro trickery to automate. You’ll probably need to look into P99 for that. The from_abv function isn’t something I’d recommend for the general case, as we have no way of guaranteeing that the next time you make iterable fields you’ll use names with underscores. (Of course, you could drop the from_abv function and give your members inscrutable names like SP, TL, and SR, allowing you to directly compare them to your string data, but you’d need to change the strcmp to a memcmp with a size argument of (sizeof(#x) - 1). Then all the places you have from_abv you’d just use from_str, which can be automatically generated for you.)

    However, from_abv isn’t hard to define, and you could honestly just copy and paste your if blocks from above into it – it’d be slightly more efficient, though if you added a “member” you’d have to update the function (as written, it’ll update itself if you add a member.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to map DbConnection to an un-opened SqlConnection using Ninject . This is
I want to see if I can map Racket structure fields to columns in
This works fine: #include <iostream> #include <map> using namespace std; struct Bar { int
Why can't I insert as shown below? #include <map> struct something { } some_object;
I have a stl::map which key type is a custom struct. I want to
Hi suppose I want to create a map of the form map<int, vector<node> >
I have an STL map that I want to iterate through, and can't seem
I want to map a INI file as a python object. So if the
I want to map a Tag entity using declarative method with SQLAlchemy. A tag
I want to map w! in vim to save a file using sudo silently

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.