Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

How to shorten the if loop?

Status
Not open for further replies.

RyanHan

Junior Member level 3
Joined
Apr 24, 2012
Messages
26
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,281
Activity points
1,514
Dear All,

I had a DataString buffer of ASCII code read from the serial port and wanted to check and process the code if it match certain pattern. My pointer x = 0 is a CR so I check the charater before CR to match certain patterns. Is there a way to shorten the code so its more readable that will also yeild a true if the string character matches? Thanks a lot


Code:
if                ((DataString0[x-7]=='T') && (DataString0[x-6]=='1') && 
	     (DataString0[x-5]=='V') && (DataString0[x-4]=='a') && 
	     (DataString0[x-3]=='l') && (DataString0[x-2]=='i') && (DataString0[x-1]=='d'))
                   {
                    .
                    .
                    .
                   }
 

Have you considered using the routines in the Standard C String library (string.h):

cstring library (string.h)

Particularly the strstr() routine.

Or is this an educational exercise or assignment?

If not, why reinvent the wheel?

BigDog
 
  • Like
Reactions: FvM

    FvM

    Points: 2
    Helpful Answer Positive Rating
Maybe you can use a define to increase the readability.
Something like

Code:
#define character(z) DataString0[x-(7-(z))]

Then you can use

Code:
if(	(character(0)=='T') &&
	(character(1)=='1') &&
	(character(2)=='V') &&
	(character(3)=='a') &&
	(character(4)=='l') &&	
	(character(5)=='i') &&
	(character(6)=='d'))
{


}

Alex
 

By utilizing pointers you could significantly reduce the redundant coding.

For example, the following is an open source implementation of the strstr() routine:

Code:
#include <string.h>
#include <libsa/stdlib.h>

__private_extern__ char *
strstr(const char *in, const char *str)
{
    char c;
    size_t len;

    c = *str++;
    if (!c)
        return (char *) in;	// Trivial empty string case

    len = strlen(str);
    do {
        char sc;

        do {
            sc = *in++;
            if (!sc)
                return (char *) 0;
        } while (sc != c);
    } while (strncmp(in, str, len) != 0);

    return (char *) (in - 1);
}

And the strncmp() routine utilized above:

Code:
int
strncmp(const char *s1, const char *s2, size_t n)
{
    for ( ; n > 0; s1++, s2++, --n)
	if (*s1 != *s2)
	    return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1);
	else if (*s1 == '\0')
	    return 0;
    return 0;
}

BigDog
 
I think you can also use a define that does the complete job
Code:
 #define CheckString(a,b,c,d,e,f,g) (DataString0[x-7]==(a)) && (DataString0[x-6]==(b)) && (DataString0[x-5]==(c)) && (DataString0[x-4]==(d)) && (DataString0[x-3]==(e)) && (DataString0[x-2]==(f)) && (DataString0[x-1]==(g))

And then

Code:
if(CheckString('T',1','V','a','l','i','d') )
{
}

Or if the characters are always the same then you can define them directly and just call CheckString.

Alex
 
Last edited:

Alex, the problem with both your methods is they still evaluate to a sequence of individual character checks, although it certianly looks nicer in the source code.
Bigdogguru's method is the standard function for sensing if one string is part of another and it uses a routine which in most cases will be faster and use less code. As a bonus, it tells you where in the string the characters forst appear although in the case of detecting a 'live' incoming stream this is of little benefit.

Brian.
 

Yes my method (basically the OP was already using it) checks a sequence of characters, I don't see why this is a problem , the if condition will exit as soon as one character doesn't match.
In addition I don't think that the string compare function does anything differently , it also compares characters , how else can it compare the strings?

I did a test in AVR mega8

Code:
char DataString0[] = "T1valid123456789";
uint8_t x; 
volatile uint8_t some_value;

x=7;
if (CheckString('T','1','v','a','l','i','d')) {some_value=100;}

The if line executes in 95 cycles.

If the second character is wrong like
Code:
if (CheckString('T','2','v','a','l','i','d')) {some_value=100;}
it just takes 28 cycles.

Can the above function give better speed, after all the routine itself uses if to compare characters plus some additional operation.
The memory usage will be definitely worse by declaring a function.

I guess it depends on what the OP wants to do but when he checks predefines positions I think an if will be faster.

Alex
 

Hi Bigdog,

I am a novice. Totally dont understand your programming at all :)
 

The use of pointers is one of the more powerful aspects of C programming.

However, you have not answered my original question.

Or is this an educational exercise or assignment?

BigDog
 

Alex, the problem with both your methods is they still evaluate to a sequence of individual character checks, although it certianly looks nicer in the source code.
Bigdogguru's method is the standard function for sensing if one string is part of another and it uses a routine which in most cases will be faster and use less code. As a bonus, it tells you where in the string the characters forst appear although in the case of detecting a 'live' incoming stream this is of little benefit.

Brian.

Alexan_e's approach is very specific for this particular case. It is doing what RayanHan wants to do with less overhead.
But ... but the hidden treasure of BigDog's approach is a kind of KMP Algorithm, if I am not wrong. Correct me .
 
Last edited:

Hi bigdog, it will an educational exercise. My program is done and working. Just want to beautify it and make reading and decoding easier for my junior the next time.
 

Hi bigdog, mind to share how your progam works? I got a lot of data patterns to compare with. Is your code going to shorten it? Thanks
 

Do you need to actually write the routines or can you use the C String Library routines?

Both my examples utilize C pointers, which are variables which store the address of other memory locations rather than values.

I would suggest studying a tutorial on the subject before I attempt to explain the above routines:

Lesson 6: Pointers in C

BigDog
 

Hi bigdog, mind to share how your progam works? I got a lot of data patterns to compare with. Is your code going to shorten it? Thanks

For that you can go for the method suggested by BigDog.
To understand the code you must know the application of pointer in C language.
To understand its power [hidden Treasure] you have to learn Searching & Sorting Algorithms and time complexity analysis.
Data structures using c & C++ by tanenbaum is a good book to start with.
 

Status
Not open for further replies.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top