C Programming - Library Functions - Discussion

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;
}

[A]. Missed
[B]. Got it
[C]. Error in memcmp statement
[D]. None of above

Answer: Option B

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".


Levin said: (Sep 14, 2011)  
If the condition is true 1 is to be returned. How 0 here ?

Prasad said: (Sep 2, 2012)  
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:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.