Function "strcmp ()" working without adding "string.h"

4

I wrote an algorithm in C that uses the strcmp() function. Even forgetting to add the string.h algorithm worked.

I would like to understand how it worked since I only found this function in the string.h library.

#include<stdio.h>
#include<stdlib.h>


typedef struct Produto{
    char nome[30];
    float preco;
}Produto;

int compara_nome(const void * A, const void* B){
Produto * pointerA=(Produto *) A;
Produto * pointerB=(Produto *) B;

return strcmp (pointerA->nome,pointerB->nome);/* como isto está funcionando sem o string.h ?*/


}
int compara_preco(const void * A, const void * B){
    Produto * pointerA=(Produto *) A;
    Produto * pointerB=(Produto *) B;
return (pointerA->preco-pointerB->preco);

}


int main(){
 static Produto Estoque[10]={{"Leite",5.50},{"Donuts",23.6},{"Detergente",4.15},{"Acucar",7.84},
 {"Brigadeiro",12.30},{"Limão",3.48},{"Morango",6.21},{"Tomate",4.12},{"Feijao",3.10},{"Skol",7.89}};

 qsort(Estoque,10,sizeof(Produto),compara_nome);

 int i;
 for(i=0;i<10;i++){
    printf("Nome: %-10s\t  Preco:%5.2f \t\n",Estoque[i].nome,Estoque[i].preco);
 }
qsort(Estoque,10,sizeof(Produto),compara_preco);    
printf("-----------------------------------------------");
printf("\n");
 for(i=0;i<10;i++){
    printf("Nome: %-10s\t  Preco:%5.2f \t\n",Estoque[i].nome,Estoque[i].preco);
 }  

    return 0;
}
    
asked by anonymous 19.12.2018 / 20:22

1 answer

5

What is in the header file is just the signature of the function, not its implementation. If implementation is available, linking will work. In this case the compiler recognizes that it is possible to call it without further checks and trusts that it will work. The ideal is not to do so because if you call it the wrong way it will give runtime error, an error that could be detected in the compilation if it had the signature evaluated.

C has many things that work but is not guaranteed to be right. Remember that C is a portable Assembly and not a high-level language with all possible checks. So I always say:

EspeciallyinCpeopleneedtobecomeaccustomedtothephilosophyofunderstandingwhatisdoingandhappeningandnottrustingtheresult.InmodernCthisisconsideredamistake.Itispossibletoconnectananalysisinthecompilertonotlethappen,Iadvisetodoit,otherwiseitwilldealwithsomethinglike"it works on my machine" that is always a problem of the programmer.

Signing is just a contract to follow, it is not something that runs a code. The execution will be inserted normally and will be twisted to make it work.

    
19.12.2018 / 20:50