전언으로 주장하다.
나는 다음과 같은 방법으로 메세지와 함께 사용되는 어딘가의 주장을 보았다.
assert(("message", condition));
gcc가 다음과 같은 경고를 던지는 것을 제외하면 이는 매우 효과가 있는 것으로 보인다.
warning: left-hand operand of comma expression has no effect
어떻게 하면 경고를 멈출 수 있을까?
사용하다-Wno-unused-value
경고를 멈추다; (옵션)-Wall
포함한다-Wunused-value
).
더 좋은 방법은 다음과 같은 다른 방법을 사용하는 것이라고 생각한다.
assert(condition && "message");
시도:
#define assert__(x) for ( ; !(x) ; assert(x) )
다음과 같이 사용하다.
assert__(x) {
printf("assertion will fail\n");
}
어설션 실패 시에만 블록 실행
중요 참고:이 방법은 표현을 평가할 것이다.
x
혹시 모르니 두 번x
로 평가하다.false
! (첫 번째, 루프가 상태를 확인할 때, 두 번째, 통과된 표현을 평가할 때!)
전통에 의하면(void)
컴파일러와 통신하여 식을 고의로 무시하는 경우:
/* picard.c, TNG S6E11. */
#define assertmsg(x, msg) assert(((void) msg, x))
assertmsg(2+2==5, "There! are! four! lights!");
예기치 않은 기본 스위치의 경우 옵션은
assert(!"message");
필요한 기능const char*
및 반환true
아마도 모든 종류의 경고로부터 당신을 구할 것이다.
#include <assert.h>
int always_true(const char *msg) {
return 1;
}
#define assert_msg(expr, msg) assert((expr) && always_true(msg))
형식화된 메시지를 전달하려면 다음 매크로를 사용하십시오.
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <assert.h>
#define clean_errno() (errno == 0 ? "None" : strerror(errno))
#define log_error(M, ...) fprintf(stderr, "[ERROR] (%s:%d: errno: %s) " M "\n", __FILE__, __LINE__, clean_errno(), ##__VA_ARGS__)
#define assertf(A, M, ...) if(!(A)) {log_error(M, ##__VA_ARGS__); assert(A); }
그런 다음 인쇄물과 같이 사용하십시오.
// With no args
assertf(self != NULL,"[Server] Failed to create server.");
// With formatting args
assertf((self->socket = u_open(self->port)) != -1,"[Server] Failed to bind to port %i:",self->port);
// etc...
출력:
[오류] (../sRC/webserver.c:180: 에러노:이미 사용 중인 주소) [서버] [서버] 포트 8080: webserver: ../src/webserver.c:180:server_run: Assertion '(self->socket = u_open(self->port) != -1'에 바인딩하지 못함
http://c.learncodethehardway.org/book/ex20.html 기반
동일한 사용법을 제공하는 매크로를 직접 작성할 수 있다._Static_assert(expr, msg)
:
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
/*
* void assert_msg(bool expr, const char *msg);
*/
#if !defined(NDEBUG)
#define assert_msg(expr, msg) do \
{ \
const bool e_ = expr; \
\
if (!e_) { \
fputs(msg, stderr); \
fputc('\n', stderr); \
assert(e_); \
} \
} while (0)
#else
#define assert_msg(expr, msg) do \
{ \
\
if (!(expr)) \
warn_bug(msg); \
} while (0)
#endif
나 또한 매크로가 있다.warn_bug()
프로그램 이름, 파일, 줄, 기능, 오류 없음 값 및 문자열, 사용자 메시지 등을 인쇄하는 기능.그 이면의 이유는 그것이 그 프로그램을 깨뜨리지 않을 것이지만, 그것은 아마 버그가 존재할 것이라고 경고할 것이다.그냥 정의를 내리면 돼assert_msg
만약이라면 텅 비어 있다defined(NDEBUG)
그래도.
다음 링크에 따르면 http://www.cplusplus.com/reference/clibrary/cassert/assert/
표현만을 기대한다고 단언하다.아마도 당신은 과부하된 기능을 사용하고 있을 것이다.
이에 따라 표현만 허용돼 이 경고를 받고 있다.
나의 경우 출력 조절이 가능하도록 @pmg의 대답을 바꿨다.그(... && "message")
나한테는 통하지 않았어
#include <assert.h>
#include <stdio.h>
#define __DEBUG__ 1
assert ((1 == 1) &&
(__DEBUG__ && printf(" - debug: check, ok.\n")) || !__DEBUG__);
참조URL: https://stackoverflow.com/questions/5867834/assert-with-message
'IT이야기' 카테고리의 다른 글
Java에서 일반 매개 변수 유형 가져오기(반영 포함) (0) | 2022.05.02 |
---|---|
axi 및 Symfony를 사용하여 개체를 삭제할 때 상태 코드 500이 삭제되지만 삭제는 작동함 (0) | 2022.05.02 |
Eclipse에서 java.library.path를 설정하는 방법 (0) | 2022.05.02 |
Vuex getter가 정의되지 않은 상태로 반환됨 (0) | 2022.05.02 |
IE 11에서 코드 블록 루핑 (0) | 2022.05.01 |