Proper way to define type (typedef vs #define)

空扰寡人 提交于 2020-12-06 04:03:03

问题


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;
    }

回答1:


You should always use the 2nd one (i.e. 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". e.g.

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



回答2:


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.




回答3:


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




回答4:


Go with the typedef. There are many reasons, but the first one that comes to mind is that the typedef applies to the scope where it is declared, but the #define ignores scope and applies to the remainder of whatever source module it is defined in. For that reason alone, the typedef is "safer".



来源:https://stackoverflow.com/questions/36518029/proper-way-to-define-type-typedef-vs-define

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!