Hello I have the following test code and I am confused about cpp.
If you declare in library.h an array with an empty element clause .. what will the compiler pick? It does also not complain, I use Cygwin.
In library.cpp I assign values to two elements, is the compiler assuming an array with one element and I write the second element outside the scope of the array?
#ifndef LIBRARY_H
#define LIBRARY_H
class library {
public:
    void print();
    char a[];
};
#endif
#include <stdio.h>
#include "library.h"
void library::print() {
    a[0] = 'a';
    printf("1. element: %d\n", a[0]);
    a[1] = 'b';
    printf("2. element: %d\n", a[1]);
}
#include <stdio.h>
#include "library.h"
void execute();
library l;
int main() {
    l = library();
    l.print();
    return 0;
}
OPTIONS=-Wall
all: main
run: main
        ./main.exe
main: client.o library.o
        g++ $(OPTIONS) -o main $^
library.o: library.cpp library.h
        g++ $(OPTIONS) -c $<
.cpp.o:
        g++ $(OPTIONS) -c $<
clean:
        rm -r *.o
                public:
     void print();
     char a[];
This code is simply illegal in C++. Array size in C++ needs to be positive compile time constant. Solution is to replace it by:
public:
      void print();
      std::string a;
Note that the declaration,
char a[];
is valid in c99 and it is known as Incomplete array type, the C standard guarantees that a can store atleast one element of the type char. This is not valid in C++. C++ standard does not allow these. Simply because both are different languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With