Proper way to define type (typedef vs #define)

Which of these methods is more secure for defining variable types? I know that we all frown when we see #defines, but it seems to work just as well as typedef here:

Is there an advantage one way or the other, and if so what might it be?

Method One:

    #include <iostream>

    #define byte unsigned char

    int main() {
        byte testByte = 'A';
        std::cout << testByte << std::endl;

        return 0;
    }

Method Two:

     #include <iostream>

     int main() {
        typedef unsigned char byte;

        byte testByte = 'A';
        std::cout << testByte << std::endl;

        return 0;
    }

You should always use the 2nd one (ie typedef or using).

Try to not use macros in c++ as far as possible, and most cases could be avoided. They're just text replacement before compiling, and more "dangerous". eg

#define byte_pointer unsigned char*
byte_pointer p, q; // only p is a pointer

Only one of your examples actually is a way to define a type, so there's no contest between them.


#define byte unsigned char

This just makes all utterances of byte in your code get replaced with unsigned char before compilation begins. It does not define a type.

The declaration int byte; will become int unsigned char; , which is nonsense.


typedef unsigned char byte;

This defines a type. The type will be subject to syntax rules, scoping rules and all of that lovely stuff.

The declaration int byte; will still be the declaration int byte; , because byte here is found in the space for a variable name.


using byte = unsigned char;

This is the "modern" way to define a type alias, which has much clearer syntax than a typedef statement (especially for more complex types).

It was introduced because otherwise the new syntax for template type aliases would have been next to impossible to make sane.


Using #define is not safe (see other answer) Using typedef is the usual way to define types aliases.

There's also the new "using" syntax

using MyByte = unsigned char;

see this answer to a related question (typedef vs. using) https://stackoverflow.com/a/10748056/446303

链接地址: http://www.djcxy.com/p/78654.html

上一篇: 如何声明一个函数返回一个指向函数的指针返回指向int [3]

下一篇: 正确的方式来定义类型(typedef vs #define)