Go Down

Topic: gibberish at the end of a string (Read 1 time) previous topic - next topic

nickgammon

#15
Jun 06, 2015, 09:56 am Last Edit: Jun 06, 2015, 09:58 am by Nick Gammon
Maybe memset?

Code: [Select]

  char foo[5];
  memset (foo, '.', sizeof (foo) - 1);
  foo [sizeof (foo) - 1] = 0;


Then it will work for any size string.
Please post technical questions on the forum, not by personal message. Thanks!

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

racpi

#16
Jun 06, 2015, 10:23 am Last Edit: Jun 06, 2015, 10:23 am by racpi
a question  .  does this produce better code than 
 
Code: [Select]
char foo[5];
  memset (foo, '.', sizeof (foo) - 1);
  foo [sizeof (foo) - 1] = 0;

this

Code: [Select]
char foo[5];
for(int i=0;i<sizeof(foo)-1;i++){
    foo[i]='.';
}
foo [sizeof (foo) - 1] = 0;

after compiling or is it pedantic semantics (could that be semantic pedantics),  I would expect any decent  optimising compiler would do pretty much the same job either way or am I wrong ?
 

richard

guy_c

Thanks Mark, my initial post started with a simplified scenario.

In real life array is not initialized upon declaration. Please see my question

guy_c

I'll post a new question on how to initialize the string termination.

nickgammon

a question  .  does this produce better code than 
 
...

after compiling or is it pedantic semantics (could that be semantic pedantics),  I would expect any decent  optimising compiler would do pretty much the same job either way or am I wrong ?
You can always try for yourself and see. :)

I tried it and the "long" way actually generated code which is 4 bytes smaller. However I think the "memset" version makes the intent instantly clear, whereas the loop you need to inspect.

Plus probably the use of a function would be more efficient if you needed to do it more than once. In fact by adding in a second initialization of foo in both sketches, the one with memset was 8 bytes shorter. So, shorter and more readable, if you need to do it more than once.

 
Please post technical questions on the forum, not by personal message. Thanks!

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

Go Up