C++ 语法和语义的区别

C++ 语法和语义的区别

语法:

  • 它是指编程语言(例如C/C++)中编写任何语句的规则和规定。
  • 它与语句的含义无关。
  • 如果语句遵循所有规则,则其在语法上是有效的。
  • 它与语言的语法和结构有关。

语义:

  • 它是指编程语言中与语句相关的含义。
  • 它关注的是解释程序的语句含义。
  • 错误在运行时处理。

程序1:

以下是演示语义错误的代码:

// C++ program to demonstrate semantic error
 
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    // Return statement before cout
    return 0;
 
    // Print the value
    cout << "GFG!";
}
// Java program to demonstrate semantic error
import java.util.*;
class GFG
{
 
// Driver Code
public static void main(String[] args)
{
   
    // exit() statement before cout
   System.exit(0);
 
    // Print the value
    System.out.print("GFG!");
}
}
 
// This code is contributed by aashish1995
# Python program to demonstrate semantic error
import sys
 
# Driver Code
if __name__ == '__main__':
 
    # exit() statement before cout
    sys.exit(0);
 
    # Print the value
    print("GFG!");
     
# This code is contributed by gauravrajput1
// C# program to demonstrate semantic error
using System;
 
class GFG
{
 
// Driver Code
public static void Main(String[] args)
{
   
    // exit() statement before cout
    Environment.Exit(0);
 
    // Print the value
    Console.Write("GFG!");
}
}
 
// This code is contributed by gauravrajput1
<script>
// javascript program to demonstrate semantic error
 
    // Driver Code
     
    // exit() statement before cout
    function fun()
    {
        return;
 
        // Print the value
        document.write("GFG!");
    }
        fun();
 
// This code is contributed by gauravrajput1
</script>

解释:

  • 输出将为空,因为上述程序的语义不正确。
  • 此程序没有语法错误,因为它遵循了每个编程规则,但它仍然不会在屏幕上打印任何内容,因为return语句先于cout语句编写,这使程序在打印任何内容之前终止。这种情况被认为是语义错误。

程序2:

以下是不带任何语法和语义错误的正确代码。

// C++ program to demonstrate basic operation // without any syntax and semantic error #include <iostream> using namespace std; // Driver Code int main() { // To print gfg cout << "GFG!"; return 0; }
// Java程序演示基本操作
// 没有任何语法和语义错误
class GFG{
 
// 驱动器代码
public static void main(String[] args)
{
     
    // 打印GFG
    System.out.print("GFG!");
}
}
 
// 此代码由aashish1995贡献
# Python3程序演示基本操作
# 没有任何语法和语义错误
 
# 打印gfg
print("GFG!")
 
# 此代码由divyeshrabadiya07贡献
// C#程序演示基本操作
// 没有任何语法和语义错误
using System;
 
public class GFG
{
 
  // 驱动器代码
  public static void Main(String[] args)
  {
 
    // 打印gfg
    Console.Write("GFG!");
  }
}
 
// 此代码由Rajput-Ji贡献
<script>
// Javascript程序演示基本操作
// 没有任何语法和语义错误
 
// 打印gfg
document.write("GFG!");
 
// 此代码由patel2127贡献
</script> 

输出:

GFG!

语法和语义错误的表格差异:

基础 语法 语义学
意义 它指的是编程语言中任何语句的规则。 它指的是编程语言中与任何语句相关的含义。
错误 它被称为语法错误。它通常在编译时遇到。当语句不符合编程语言的语法时会发生。一些例子是在C++中缺少分号,在Java中使用未声明的变量等。 它被称为语义错误。它通常在运行时遇到。当语句在语法上有效但不做程序员意图的事情时发生。这种类型的错误很难捕捉。
在语言学中 语法是单词的排列或顺序,由作者的风格和语法规则决定。 有两个语义学领域:逻辑语义和词汇语义。
灵敏度 语法在大多数编程语言中是敏感的。 大多数语义是不区分大小写的。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程