Search code examples
cconditional-statementslexical-scope

C: Cannot declare pointer inside if statement


I have a pointer which points to a function. I would like to:

  if (mode == 0)
  {
  const unsigned char *packet = read_serial_packet(src, &len);

  } else {
  const unsigned char *packet = read_network_packet(fd, &len);
  }

But I cannot do it because my compiler complains when I first use the pointer later in the code.

   error: 'packet' undeclared (first use in this function)

This is strange. It worked without the if statement, but now I need my program to be able to get data from different sources. Isn't it possible to do this? I think so. If it isn't, is there any other simple way to get what I am trying?

Thanks a lot.


Solution

  • You need to review the concept of blocks or compound-statements, or variable scope.

    If you declare a variable in a compound statement ({, }), the variable will be declared only in that exact scope.

    Thus, change your code to

    const unsigned char *packet = NULL;
    if (mode == 0)
    {
       packet = read_serial_packet(src, &len);
    } else {
       packet = read_network_packet(fd, &len);
    }
    
    // Now you can perform operations on packet.