Wednesday, May 18, 2011

Comparing NULL in C example


You can use the below code for comparing String with NULL in C

char * ff;
if (  ff != NULL ) );
{
printf("value isnot null");
}
else
{
printf ("value is null");
}

Comments in C and C++


In C

valid comments are when text are in between /*  .......*/
It can also be used across multiple lines.But it will not support nested comments.

ex:
/*  comments  */
or

/*   First line
Second line  */

It can also be used like:
/*  comments
*   comments
*  comments
*/

 new C compilers also supports inline comments    // .  but old compilers may give syntax error.
ex:
int c;  // for intializing

 C++  supports both type of comments inline comments // and /*  ...*/




strcmp and strncmp in C


strcmp function in c

int strcmp(char * str1,char * str2)
strcmp function  returns a number eitheir 0, positive integer or negative integer

Return vaues:

positive integer       - is returned if string str1 is greater than string str2
0                           - if both the strings are equal
negative integer      -  if string str1 is less than the string str2


In this case comparisons happen using unsigned integers.

for example:
char * i = "hello";
char * j="hello1"; 
printf("%d",strcmp(i,j));
output will be a negative integer

 strncmp in C:

The syntax all are same .but in this case there is an extra argument for setting how many characters you want to compare.

int strncmp(char *str1,char * str2, int );

Functionality all are same.But here int parameter is to set no of characters to compare in two strings.


for example:
char * i = "hello";
char * j="hello1"; 
printf("%d",strcmp(i,j,4));
output will be 0 as we compare only 4 characters and it is same in both the strings.