Daiwik Daarun
Daiwik Daarun

Reputation: 3974

How to #define a character in C++

I need to define a character in C++. Right now I have:

#define ENQ (char)5

Is there a way to define a character similar to how you can define a long using the l suffix (e.g. 5l)?

Upvotes: 1

Views: 5711

Answers (3)

Clifford
Clifford

Reputation: 93476

The cast is fine, it has no run-time impact, but you can define character constants of any value directly using the \x escape sequence to specify characters by their hexadecimal character code - useful for non-printing or extended characters.

#define ASCII_ENQ `\x5`

But in C++ you'd do better to use a const (which has explicit type):

static const char ASCII_ENQ = 5 ;

or

static const char ASCII_ENQ = '\x5' ;

if you strive for complete type agreement (not really necessary).

Upvotes: 5

Bob__
Bob__

Reputation: 12759

You can also use an User-defined literals and write something like this:

#include <iostream>

const char operator ""_ch( unsigned long long i) {
    return i;
}

int main() {
    char enq = 5_ch;
    char alpha = 65_ch;

    cout << alpha << '\n';

    return 0;
}

But it's a bit of overkill for something you can more easily express with:

const char ENQ = 5;

Unless you are actually trying to do things as tricky as:

#include <iostream>

// convert a number (a figure) to its ASCII code
const char operator ""_ch( unsigned long long i) {
    return i < 10 ? i + 48 : 48;
}

int main() {
    char num_as_char = 5_ch;

    std::cout << num_as_char << '\n';
    // which outputs 5
    return 0;
}

Upvotes: 1

bolov
bolov

Reputation: 75727

that would be a character literal 'a' for instance:

#define ALPHA 'a'
#define FIVE_CHAR '5'

Upvotes: 1

Related Questions