Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
How does strlen function works in c?

The source code I found for strlen function in c is the one in below:

int
strlen(string)
    char *string;       /* String whose length is wanted. */
{
    register char *p = string;

    while (1) {
    if (p[0] == 0) {
        return p - string;
    }
    if (p[1] == 0) {
        return p + 1 - string;
    }
    if (p[2] == 0) {
        return p + 2 - string;
    }
    if (p[3] == 0) {
        return p + 3 - string;
    }
    p += 4;
    }
}

The link is this. I don't understand why the steps are 4. The function jumps 4 bytes by 4 bytes over the string. Why it does this way? It could be implemented like this:

int
strlen(string)
    char *string;       /* String whose length is wanted. */
{
    register char *p = string;

    while (1) {
    if (*p == 0)
        return p - string;
    p += 1;
    }
}

Is there any performance related reason behind it?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

This is called "loop unrolling" and is done purely for performance reasons. Modern compilers are perfectly good at doing their own loop unrolling, so doing it manually is likely going to hurt performance relative to the compiler's generated code.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda