Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using define macro and its value in quotes

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?

like image 543
setevoy Avatar asked Jan 25 '19 10:01

setevoy


People also ask

What is correct way to define macro?

A macro is an automated input sequence that imitates keystrokes or mouse actions. A macro is typically used to replace a repetitive series of keyboard and mouse actions and used often in spreadsheets and word processing applications like MS Excel and MS Word.

How do you define macro explain it with example?

In computer programming, macros are a tool that allows a developer to re-use code. For instance, in the C programming language, this is an example of a simple macro definition which incorporates arguments: #define square(x) ((x) * (x))

What is macro explain macro with arguments?

Macro Arguments (DEFINE-! ENDDEFINE command) The macro definition can include macro arguments, which can be assigned specific values in the macro call. There are two types of arguments: keyword and positional. Keyword arguments are assigned names in the macro definition; in the macro call, they are identified by name.


1 Answers

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.

like image 116
Sourav Ghosh Avatar answered Sep 18 '22 10:09

Sourav Ghosh