c++断言设置

利用断言来检测调用的子函数的前置条件。
包含#include<cassert>
用函数assert来判断条件是否符合。assert(c>150)
当C大于150的时候,即括号里面的条件为真,则不采取任何行动。当条件为假时,则显示一条错误的消息。显示的错误信息
简单代码介绍

#include<iostream>
#include<cassert>
using namespace std;
int  add(int a, int b);


void main()
{
    int a = 11;
    int b = 5;
    //int b=15;
    //assert(b > 10);
    int c = add(a, b);
    cout << c << endl;
    getchar();
}

int  add(int a, int b)
//前置条件是b必须为大于10的数,
//防止在中调用的时候错用b的值,
//应该在子函数中或者在主函数中加入断言函数,来判断。
{
    int c = a + b;
    assert(b > 10);
    return (c);
}
发布了53 篇原创文章 · 获赞 24 · 访问量 17万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章