Go Down

Topic: why DOES this code work.. (Read 361 times) previous topic - next topic

eddiea6987

Code: [Select]

void sendString ( char *myString)
{
while (*myString> 0)
{
sendChar(*myString++);

}
}


when i send a string it displays it properly, but if i increment my string pointer from the get go it never sees index 0 which would be the first letter yet it does in fact display it ;
how so? is there a null character in beginning of my string?

the way i see is it like any array
"EDDIE"
0 1 2 3 4
E D D I E    <--see the E in the 0 position
but the very first operation in the while loop is *pointer++  so right there it goes to position one which is the first D...

im lost here :(
I could print the Arduino logo on a box of cereal and sell it as "Arduin-O's"

Henry_Best

"I could print the Arduino logo on a box of cereal and sell it as "Arduin-O's"

Cereal communication...

Nick Gammon

It's a post-increment, that's why. It wouldn't work if you wrote:

Code: [Select]

sendChar(*++myString);
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

holmes4

Post increment, i++, increments after the value has been used, pre increment increment before use.

So your code reads
Code: [Select]
void sendString ( char *myString)
{
while (*myString> 0)
{
sendChar(*myString);
                *myString++;

}
}


C++ means c incremented (improved) after use  :)

Mark

majenko

Let's break it down:

Code: [Select]


while (*myString> 0)
{
sendChar(*myString++);

}

While the character is greater than 0:
- Print the character
- Increment the pointer

Code: [Select]

while (*myString++> 0)
{
sendChar(*myString);

}
 
While the character is greater than 0:
- Increment the pointer
- Print the character

See the subtle difference?  The ++ is performed after the test, *not* after each iteration of the while loop.  You could do it with a do...while loop though, and preincrement, as long as the first character is guaranteed NOT to be 0:
Code: [Select]

do {
   sendChar(*myString);
} while (*(++myString) > 0);

majenko


C++ means c incremented (improved) after use  :)

Personally I thought it was a reference to the standardized language used in 1984 (George Orwell) - C that is double-plus good.

Go Up