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

I wrote an algorithm in C that uses the function strcmp(). Even forgetting to add the string.h the 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;
}
Author: Maniero, 2018-12-19

1 answers

What is in the header file is only the Signature of the function, not its implementation. If the implementation is available, in linkedition 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 called wrongly it will give an error at runtime, an error that could be detected in the build if it had the signature evaluated.

C has many things that they work but it's 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:

Fiat 147 all detonated walking the streets

Especially in C people need to get used to the philosophy of understanding what is doing and happening and not trusting the outcome. In modern C this is considered a mistake. Is it possible to turn on an analysis in the compiler to not let it happen, I advise to do it in case otherwise it will deal with something like "works on my machine" which is always a programmer problem.

Signature is just a contract to be followed, it is not something that executes a code. The execution will be inserted normally and twisted to make it work.

 5
Author: Maniero, 2020-08-20 18:53:55