6

Writing some C code just out of curiosity and I'd like to move some values for a MySQL connection to a kind of const.

Question 1 Is it a good idea to store host, user etc in preprocessor macros? I.e.:

#include <my_global.h>
#include <mysql.h>

#define DB_HOST "mysqlhost.com"
#define DB_USER "mysqlusername"
#define DB_TABLE "tablename"
...

To use them later like mysql_real_connect(con, DB_HOST, DB_USER, DP_PASS, DB_NAME, 0, NULL, 0) == NULL) ?

Question 2

Can I use DB_TABLE's value inside a quoted string? I.e. mysql_query(con, "SELECT * FROM DB_TABLE")

If so - what is corrcect way to use it here?

alk
  • 69,737
  • 10
  • 105
  • 255
setevoy
  • 4,374
  • 11
  • 50
  • 87
  • 2
    Regarding the first question, check this answer about the advantages of const vs define (vs enum): https://stackoverflow.com/a/1674459/7520531 – Jose Jan 25 '19 at 11:11

2 Answers2

6

Answer 1: Technically, you can define it the way you have shown, but at times, it makes sense to make the parameters which are likely to change (like hostname, username) as environment variables, and read them during the program execution. This makes your program more robust against frequent changes. The parameters which are to remain same, can surely be used as a #define preprocessor (like tablename).

A sample can be found here.

Answer 2: No, you cannot use it like that. However, since pre-processor MACROS are compile time substitution, you can take advantage of string concatenation, like

mysql_query(con, "SELECT * FROM " DB_TABLE);

where DB_TABLE is defined as a MACRO.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
4

Is it a good idea to store host, user etc in preprocessor macros?

It is common practise, at least if the values can be considered constant in the context of the program.

Alternatively you can define constants by doing:

const char * db_host = "localhost";

The drawback here is that the simple concatenation as shown below won't work.

Can I use DB_TABLE's value inside a quoted string?

No, but you can just do:

mysql_query(con, "SELECT * FROM " DB_TABLE);
alk
  • 69,737
  • 10
  • 105
  • 255
  • @SouravGhosh: Absolutely! – alk Jan 25 '19 at 10:55
  • 1
    I don't think that is common practice to store values such as hostname and username in MACROS! ... It's common for very small applications ... ;) – Sir Jo Black Jan 25 '19 at 10:58
  • 2
    @SirJoBlack: Well I, generalised the question to whether it were common to #define strings. If to do so for host or user names made sense at least depends .... Reworded my answer. – alk Jan 25 '19 at 11:02