1
#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.

1
  • another thing is that ((strlen(s) - strlen(t)) > c) ? strlen(s) : strlen(t) will evaluate strlen again when returning after the comparison. Don't do that, store the lengths into variables first Commented Apr 12, 2020 at 13:24

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

strlen will actually count each time you call, so it would be better to call it once for s and once for t and store it in a variable to use in the len assignment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.