Sanjay Verma
Sanjay Verma

Reputation: 101

String function in c programming

#include<stdio.h>
#include<string.h>

void printlength(char *s, char *t) {
    unsigned int c=0;
    int len = ((strlen(s) - strlen(t)) > c) ? strlen(s) : strlen(t);
    printf("%d\n", len);
}

void main() {
    char *x = "abc";
    char *y = "defgh";
    printlength(x,y);
}

strlen is defined in string.h as returning a value of type size_t, which is an unsigned int. The output of the program is? O/P is 3 in answer

My Understanding: i know strlen function will return the length of string excluding null but i got 5.

Upvotes: 1

Views: 206

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

The standard C function strlen has the return type size_t. It is an unsigned integer type.

So a difference like this strlen(s) - strlen(t) is always greater than or equal to 0.

As a result your original function will output 3 because the difference strlen(s) - strlen(t) will yield a big positive number.

If you are going to output the maximum length of two strings then the function can look the following way

void printlength( const char *s, const char *t ) 
{
    size_t n1 = strlen( s );
    size_t n2 = strlen( t );

    size_t len = n1 < n2 ? n2 : n1;

    printf( "%zu\n", len );
}

If you want to output the minimum length of two strings then the function will look like

void printlength( const char *s, const char *t ) 
{
    size_t n1 = strlen( s );
    size_t n2 = strlen( t );

    size_t len = n2 < n1 ? n2 : n1;

    printf( "%zu\n", len );
}

Thus the maximum length returned by the first function will be equal to 5 while the minimum length returned by the second function will be equal to 3.

Here is a demonstrative program.

#include <stdio.h>
#include <string.h>

void printlength1( const char *s, const char *t ) 
{
    size_t n1 = strlen( s );
    size_t n2 = strlen( t );

    size_t len = n1 < n2 ? n2 : n1;

    printf( "%zu\n", len );
}

void printlength2( const char *s, const char *t ) 
{
    size_t n1 = strlen( s );
    size_t n2 = strlen( t );

    size_t len = n2 < n1 ? n2 : n1;

    printf( "%zu\n", len );
}
int main(void) 
{
    const char *s = "abc";
    const char *t = "defgh";

    printlength1( s, t );
    printlength2( s, t );

    return 0;
}

Its output is

5
3

Upvotes: 2

Related Questions