C assert() with Line Numbers: Debugging Made Easier
In C, the assert macro is typically used to test for certain conditions and terminate the program if the condition is false. When an assertion fails, it prints an error message that includes the line number where the assertion occurred.\n\nTo include the line number in a custom print statement, you can use the __LINE__ macro, which is a predefined macro in C that expands to the current line number in the source file.\n\nHere's an example of using assert and __LINE__ together to print the line number when an assertion fails:\n\nc\n#include <assert.h>\n#include <stdio.h>\n\nint main() {\n int x = 5;\n int y = 10;\n\n assert(x == y && "x and y must be equal"); // Assertion with a custom error message\n\n // If the assert fails, the program will terminate and print an error message including the line number\n\n printf("All assertions passed.\n");\n\n return 0;\n}\n\n\nIn this example, if the assertion x == y fails, the program will terminate and print an error message like this:\n\n\nAssertion failed: (x == y && "x and y must be equal"), function main, file example.c, line 9.\n\n\nThe line number, line 9 in this case, is automatically included in the error message.
原文地址: https://www.cveoy.top/t/topic/pYel 著作权归作者所有。请勿转载和采集!