C Programming - Library Functions - Discussion

Discussion Forum : Library Functions - Find Output of Program (Q.No. 6)
6.
What will be the output of the program?
#include<stdio.h>
#include<string.h>

int main()
{
    char dest[] = {97, 97, 0};
    char src[] = "aaa";
    int i;
    if((i = memcmp(dest, src, 2))==0)
        printf("Got it");
    else
        printf("Missed");
    return 0;
}
Missed
Got it
Error in memcmp statement
None of above
Answer: Option
Explanation:

memcmp compares the first 2 bytes of the blocks dest and src as unsigned chars. So, the ASCII value of 97 is 'a'.

if((i = memcmp(dest, src, 2))==0) When comparing the array dest and src as unsigned chars, the first 2 bytes are same in both variables.so memcmp returns '0'.
Then, the if(0=0) condition is satisfied. Hence the output is "Got it".

Discussion:
2 comments Page 1 of 1.

Levin said:   1 decade ago
If the condition is true 1 is to be returned. How 0 here ?

Prasad said:   1 decade ago
When we compare the string if each char matches then it returns 0. Else if ascii equ of fst string is greater then postive value ie difference of two strings is return else difference of two strings negative value will be returned. Hope it helped.

Post your comments here:

Your comments will be displayed after verification.