简体   繁体   English

禁用 C++ 中的检查语句

[英]Disabling check statements in C++

Say that my main code calls functions like myarray(i) where the length of myarray is N .假设我的主要代码调用myarray(i)之类的函数,其中myarray的长度为N During the development I would probably want to have a CheckIndex function inside the () overload.在开发过程中,我可能希望在()重载中有一个CheckIndex function。 However, this turns out to waste computation time when the number of iterations is large.然而,当迭代次数很大时,这会浪费计算时间。 Another example would be to check if there is consistency in the dimensions of two matrices before adding them, or checking if the denominator in this expression my_2D_array_instance/value where value is a double , is not too small or zero.另一个例子是在添加两个矩阵之前检查它们的维度是否一致,或者检查这个表达式my_2D_array_instance/value中的分母,其中value是一个double ,不是太小或为零。

My question is if there is a way to give the option to the user to tell the compiler "skip those checks" and if yes, how to do it?我的问题是,是否有办法让用户选择告诉编译器“跳过这些检查”,如果是,该怎么做?

As πάντα ῥεῖ stated in the comment section you can use preprocessor conditionals to avoid compiling code you don't want to be part of the compilation, take the code:正如评论部分中的 πάντα ῥεῖ 所述,您可以使用预处理器条件来避免编译您不想参与编译的代码,请使用以下代码:

    std::array<int, 5> a{1, 2, 3, 4, 5};

#ifdef DEBUG
    std::cout << a.at(5); //out of range
#endif

    std::cout << a.at(3);

With a normal compiler instruction the code inside #ifdef will not be compiled, but if you define DEBUG (you can name it whatever you want), when you compile it, ie :使用普通的编译器指令, #ifdef中的代码不会被编译,但是如果你定义DEBUG (你可以随意命名它),当你编译它时,

g++ main.cpp -Wall -Wextra -pedantic -D DEBUG 
                                     ^^^^^^^^

All the code will be compiled.所有代码都将被编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM