Four debugging tips in C + + programming

Source: Internet
Author: User
Tags assert bool command line include
C++| Programming | skills 1. Debug Mark

Applicable preprocessing #define defines one or more debug tags, which are managed using #ifdef and #endif in the code. When the program is finished debugging, you just need to use the #undef tag and the debugging code disappears. Common debugging marks are debug, statement sequence:

#define DEBUG
#ifdef DEBUG
调试代码
#endif

2. Debug mark during Run

Turn debug marks on and off during program run. Can be achieved by setting a debug bool tag. This is more convenient for programs that run on the command line. For example, the following code:


#include<iostream>
#include <string>
using namespace std;
bool debug =false;
int main(int argc,char*argv[])
{
  for(int i=0;i<argc;i++)
   if(string(argv[i])==“--debug=on“)
   debug = true;
   bool go=true;
   while(go)
   {
    if(debug)
    {
     调试代码
    }else {}
   }
}

3. Convert variables and expressions to strings

But using string operators to implement the transformation output definition


#define PR(x) cout<<#x”=”<<x<<'\n'

4, the C language assert ()

The macro is in, and when using Assert, give him an argument, an expression that is interpreted as true. The preprocessor produces the code that tests the assertion, and if the assertion is not true, an error message is sent telling the assertion what it is and if it fails for a while, the program terminates.


#include< assert>
using namsapce std;
int main()
{
  int i=100;
  assert(i!=100);
//Fails
}
When the commissioning is finished, before #include<assert>
Add #define NDEBUG to eliminate red-generated code
}



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.