Better constant definition approach

-5

While exploring SQLite source code for learning purposes I found this in many places within the source code;

#define SQLITE_LOCK_NONE          0
#define SQLITE_LOCK_SHARED        1
#define SQLITE_LOCK_RESERVED      2
#define SQLITE_LOCK_PENDING       3
#define SQLITE_LOCK_EXCLUSIVE     4

#define SQLITE_IOCAP_ATOMIC                 0x00000001
#define SQLITE_IOCAP_ATOMIC512              0x00000002
#define SQLITE_IOCAP_ATOMIC1K               0x00000004
#define SQLITE_IOCAP_ATOMIC2K               0x00000008
#define SQLITE_IOCAP_ATOMIC4K               0x00000010

Is this standard in modern C++ (C++11, 14, 17) or are there different ways to do this in modern C++?

c++
c++14
asked on Stack Overflow Jul 29, 2017 by Amani • edited Aug 6, 2017 by kiamlaluno

1 Answer

1

As far as I know there never was a reason to use #define for constants in C++. You can always write

const int my_constant = 42;

For your case you probably want an enum

enum SQLITE_LOCK {SQLITE_LOCK_NONE, SQLITE_LOCK_SHARED, SQLITE_LOCK_RESERVED, 
      SQLITE_LOCK_PENDING, SQLITE_LOCK_EXCLUSIVE };

And that is something that really improved a lot in c++11, as you can now use scoped enums as

enum class SQLITE_LOCK { .... };

PS: modern C++ also has constexpr for compile time constants, but I am not familiar enough to say anything about it.

answered on Stack Overflow Jul 29, 2017 by largest_prime_is_463035818 • edited Jul 29, 2017 by largest_prime_is_463035818

User contributions licensed under CC BY-SA 3.0