c++codeblocksmingw32gcc7

C++ Function error -- could not convert brace-enclosed initializer list to char*


New to C++, more familiar with MATLAB and Arduino. I'm trying to create (read: modify someone else's code) a C++ function to send a character array over serial--it's interacting with a C library (rs232.h). I keep getting this error when initializing the default value for the mode--bits/baud/parity array in the function initialization. Not sure if I am trying to do something that is not supported, if so, I can split up the variables. Thanks in advance for any help.

IDE: Code::Blocks

Compiler: MinGW-g++/GCC 7.3

Errors:

error: could not convert '{'8', 'N', '1', 0}' from '<brace-enclosed initializer list>' to 'char*'

Code:

#include <stdlib.h>
#include <stdio.h>
#include <Windows.h>
#include "rs232.h"
#include <string> /* Probably unnecessary */

bool Write(char (&toWrite)[256], int portNum=3, int bdrate=9600, char mode[]={'8','N','1','\0'})
{
  int i, cport_nr = portNum - 1;
  if(RS232_OpenComport(cport_nr, bdrate, mode))
  {
    return false;
  }
  while(1)
  {
    RS232_cputs(cport_nr, toWrite);
    printf("sent: %s\n", toWrite);
    Sleep(1000);
    i++;
    i %= 2;
  }
  return true;
} 

Solution

  • Put the default value at a separate line:

    bool Write(char (&toWrite)[256], int portNum=3, int bdrate=9600, char *mode=NULL) {
        char mode_default[] = {'8','N','1','\0'};
        if (mode == NULL) mode = mode_default;
    

    Reason:

    You cannot use default values with C array parameters (which really decay to pointers here) – UnholySheep