语法错误和语义错误

来源:互联网 发布:改图片格式的软件 编辑:程序博客网 时间:2024/06/04 18:06
语法和语义错误


编程很难,有很多方法可以犯错误。错误通常分为两类:语法错误和语义错误(逻辑错误)。


语法错误发生时,你写了一个声明针对C++语言的语法无效。这包括错误如缺少分号,未声明的变量,不匹配的括号或大括号,和未结束的字符串。例如,下面的程序包含了相当多的语法错误:

#include <iostream>; // preprocessor statements can't have a semicolon on the end int main(){    std:cout < "Hi there; << x; // invalid operator (:), unterminated string (missing "), and undeclared variable    return 0 // missing semicolon at end of statement}
幸运的是,编译器通常会捕获语法错误并生成警告或错误,因此您很容易识别和修复问题。那就只需要再编译一遍,直到你消除所有的错误。


一旦你的程序编译正确,让它实际生成你想要的结果可能会很棘手。语义错误发生时,语句在语法上是有效的,但不做程序员想要的。


有时这些会导致程序崩溃,例如在除以0的情况下:


#include <iostream> int main(){    int a = 10;    int b = 0;    std::cout << a << " / " << b << " = " << a / b; // division by 0 is undefine
有时这会产生错误的价值:

1234567#include <iostream> int main(){    std::cout << "Hello, word!"; // spelling error    return 0;}