Scope of C + + typedef and # define

Source: Internet
Author: User

typedef

If it is placed outside all functions, its scope is from the beginning of its definition until the end of the file;

If placed within a function, the defined field is defined from the beginning of the definition until the end of the function;

#define:

Scopes are defined from the beginning of the definition to the end of the entire file, whether within a function or outside of all functions.

Define within the same compilation unit, even in different namespaces, the scope of the action is the same. That is, from definition to file introduction.

Look at the following example:

Main.cpp

 /** * @file Main.cpp * @author Chenjiashou ([email protected]) * @date 2017/09/19 17:37:33 * @version $Revision $ * @brie F * **/#include<iostream>#include"Test1.h"#defineLL 2typedefLong Longll;voidTest_typedef () {typedefintX_int;x_int a=1;}namespaceOther {#defineOther//Don't care if you're in a namespace//Key in a compilation unit}intMain () {#ifdef LL std::cout<<"LL Define"<<Std::endl;#endif#ifdef SS std::cout<<"SS Define"<<Std::endl;#endif#ifdef Other Std::cout<<"Other define"<<Std::endl;#endifll a=1;    Print (); //X_int b = 1;//Compile Error    return 0;}/*vim:set ts=4 sw=4 sts=4 tw=100*/

Test1.h

/* * * @file test1.h * @author Chenjiashou ([email protected]) * @date 2017/09/19 17:39:05 * @version $Revision $  * @br Ief  *   **/#ifndef test1_h#define test1_h#endif  // Test1_h void print (); /* */

Test1.cpp

 /** * @file test1.cpp * @author Chenjiashou ([email protected]) * @date 2017/09/19 17:36:15 * @version $Revision $ * @br IEF * **/#include<iostream>#defineSS 1voidprint () {#ifdef SS std::cout<<"SS Define"<<Std::endl;#endif#ifdef LL std::cout<<"LL Define"<<Std::endl;#endif//ll C = 1;//Compile Error//std::cout << c << Endl;}/*vim:set ts=4 sw=4 sts=4 tw=100*/

Final Result:

LL Defineother definess Define

Scope of C + + typedef and # define

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.