25

Almost forgot how beautiful C is:

3 statements tell you if two strings are similar.

Comments
  • 19
    The price of that beauty is a segfault if you somehow have lost the zero termination. strncmp to the rescue.

    But the greatness of these functions is that C programmers actually know the performance issues of that stuff, even more with repeated strcat. Thats why C programs are often so fast.
  • 0
  • 1
    you have to check for both string's null termination.
  • 1
    @gnulinuxer4fun it's already checked for.
  • 1
    @electrineer only the first one
  • 2
    @gnulinuxer4fun
    *string1 == *string2 gets evaluated before *string1 == '\0'
  • 0
    This magic basically happens every time every kind of language get compiled or interpreted, reproducing those steps like C do when a string should be compared to another
  • 0
    @simulate except if string2 is shorter than string1 you access a pointer that isn't allocated, by doing that - segfault.
  • 2
    @gnulinuxer4fun it's still checked for. You don't access anything but return non-zero.
  • 0
    @electrineer try it out with a smaller second string
  • 0
    @gnulinuxer4fun try yourself
  • 0
    @electrineer not my problem if you have bad code in your codebase :shrug:
  • 0
    @gnulinuxer4fun not my problem if you can't read code. ;)
  • 0
    @gnulinuxer4fun on line 23, string1 could be replaced with string2 and the code would perform the same.
  • 3
    @gnulinuxer4fun no, if string2 is smaller (meaning that you reach \0 before string1 does) it exits the loop and return non-zero, segfault in this case is impossible if both string have \0, it segfaults if you follow what @Fast-Nop said.
  • 1
    @deodexed @simulate

    Whoops, looks like My criticism was wrong, sorry.

    *changes code in his codebase*
  • 0
    Yes, C can have some beauty to it... But C-strings are just an invitation to fuck up.
Add Comment