I’m writing a C program that connects to a postgreql db.I’m trying to check for a table :
PGresult *re=PQexec(connection, "SELECT to_regclass('fp_stores_data')");
this variable is a global variable. but when I compile the code this error occurs:
db.c:6:20: error: initializer element is not constant 6 | PGresult const *re=PQexec(connection, "SELECT to_regclass('fp_stores_data')");
Advertisement
Answer
If this is a global variable, C requires that it be initialized with something known at compile time; if it requires a call to PQexec()
, this is a runtime thing and not allowed (as your compiler has told you).
If the variable needs to remain global, best is to initialize the re
variable to NULL, and move the actual PQexec()
call/assignment into runtime code just after the database connection has been established.
A non-database example: you cannot initialize any static variable with a runtime call, so:
FILE *infile = fopen("myfile.txt", "r"); // NO int main() { infile = fopen("myfile.txt", "r"); // YES ...
It’s ok for the variable to be static; it’s only the assignment that must be made at runtime.
Alternatively, if the variable is local, it can be initialized with a runtime call.