I'm not sure if I chose the right Title, but today I discovered (as a beginner in C) that for me strlen is not always the right decision to be made when I need it.
So I tried the following:
#include<stdio.h>
#include<string.h>
int foo(char *s){
int len = strlen(s);
/* code here */
return len;
}
int main(void){
char *name = "Michi";
int len = foo(name);
int a = 20, b = 10, c = a - b;
if(c < len){
printf("True: C(%d) < Len(%d)\n",c,len);
}else{
printf("False: C(%d) > Len(%d)\n",c,len);
}
return 0;
}
Output:
False: C(10) > Len(5)
But when I compile with "-Wconversion" I get:
program.c:5:19: warning: conversion to ‘int’ from ‘size_t’ may alter its value [-Wconversion] int len = strlen(s); ^
A quick fix will be to cast strlen:
int len = (int)strlen(s);
But I was not agree, so I decided that I really need something else, another approach maybe? I tried the following:
#include<stdio.h>
#include<string.h>
unsigned int size(char *s){
unsigned int len;
/* code here */
len = (unsigned int)strlen(s);
return len;
}
int main(void){
char *name = "Michi";
unsigned int len = size(name);
int a = 20, b = 10, c = a - b;
if(c < (signed int)len){
printf("True: C(%d) < Len(%d)\n",c,len);
}else{
printf("False: C(%d) > Len(%d)\n",c,len);
}
return 0;
}
But I still need to cast strlen because of its return type (size_t which I know that is an unsigned type (typedef long unsigned int size_t;))
Finally I decided for another approach, to create my own function, which make things easier and with less possible future problems and I got:
#include<stdio.h>
long int stringLEN(char *s){
int i = 0;
long int len = 0;
while (s[i] != '\0'){
len++;
i++;
}
return len;
}
long int foo(char *s){
long int len = stringLEN(s);
/* code here */
return len;
}
int main(void){
char *name = "Michi";
long int len = foo(name);
int a = 20, b = 10, c = a - b;
if(c < len){
printf("True: C(%d) < Len(%ld)\n",c,len);
}else{
printf("False: C(%d) > Len(%ld)\n",c,len);
}
return 0;
}
where no cast is needed anymore.
So my QUESTION is: is this (for my case) a better approach ? If not I need some explanations, my books (I have 3) does not explain me in that way that I can understand this things.
I know only that at some point cast could be a big problem, somehow.
EDIT: This code will also not compile with -Wconversion:
#include<stdio.h>
#include<string.h>
size_t foo(char *s){
size_t len = strlen(s);
/* code here */
return len;
}
int main(void){
char *name = "Michi";
size_t len = foo(name);
int a = 20, b = 10, c = a - b;
if(c < len){
printf("True: C(%d) < Len(%zu)\n",c,len);
}else{
printf("False: C(%d) > Len(%zu)\n",c,len);
}
return 0;
}
Output:
error: comparison between signed and unsigned integer expressions [-Werror=sign-compare]|
But if I cast len works. I realized that, if the size is bigger then that int it will never fit.