-1

I am trying to use strtok(). Following is the piece of code that I wrote. It does not work but prints ", '" infinitely.

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

int main(){
char str[]="this, by the way, is a 'sample'";
char *tokens;
tokens = strtok(str, ", '");
//printf("%s\n",tokens);
//printf("%s\n", str);
while(tokens!=NULL)
{
    printf("%s\n", tokens);
    tokens = (NULL, ", '");
}
return 0;
}

Following is the code from a strtok() manual page, which works perfectly fine.

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

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

I feel I have done the exact same thing. Can't figure out the fault in my code. Could someone please point out.

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
nish
  • 6,952
  • 18
  • 74
  • 128
  • The duplicate marked this question is complete wrong! in this question OP forgot name of function in codding and because of `,` comma operator's behavior no error generated While linked question is about the behavior of operator. – Grijesh Chauhan Feb 01 '14 at 19:13

1 Answers1

10

Interesting bug! You forgot function name. Notice inside while-loop body following expression:

tokens =  (NULL, ",'");
         ^ 
          'strtok' missing 

should be:

tokens = strtok(NULL, ",'");

Interesting thing is that this is not a compilation error, in fact:

tokens = (NULL, ",'");

is a valid expression which is equals to:

tokens = ",'";

(Note: NULL has no side effects)

Read: Comma Operator: ,

The comma operator , has left-to-right associativity. Two expressions separated by a comma are evaluated left to right. The left operand is always evaluated, and all side effects are completed before the right operand is evaluated.

Due to parenthesis ( ) at rhs of =, after evaluating , operator right hand operand "," is assigned to token. And because token never assigned NULL so while(tokens != NULL) never breaks, and this is the reason that you are getting "," infinitely!

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208