C语言基本结构

Terwer C/C++评论186字数 1085阅读3分37秒阅读模式

第一个 C 语言程序

#include <stdio.h>

main() {
    printf("Hello, World!\n");
}

保存文件为 hello.c文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

编译

cc hello.c

运行

./a.out

如下文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

➜  clangcode cc hello.c
hello.c:3:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int]
main() {
^
1 warning generated.
➜  clangcode ./a.out   
Hello, World!

分析

#include <stdio.h> // 包含有关标准库的信息文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

main() { // 定义 main 函数,不接受参数,main 函数的语句包含在花括号中
printf("Hello, World!\n"); // main 函数调用库函数 printf 打印字符序列,\n 代表换行符
}文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

总结

每一个 C 函数,都由变量和函数组成。文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

printf 不会自动换行,无论多少个 printf 语句。文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

printf("hello,");
printf("world");
printf("\n");

// 打印结果如下
// hello,world

\n 只代表一个字符。文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

类似 \n 这样的字符为不能打印或者不可见字符提供了通用的扩展机制。文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

其他的换码序列还有:文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

制表符 \t
回退符 \b
双引号 \"
反斜杠本身 \\

注意:当输入的转义字符不受支持时,会原样输出,且编译和运行都不会报错。文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

实战

VC6

下面三种写法在 Microsoft Visual C++ 6.0 都可以编译通过并执行成功。文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

最后一种虽然能运行通过,但是编译有警告 warning C4508: 'main' : function should return a value; 'void' return type assumed​,前两种写法都不会有警告。文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

#include "stdafx.h"

int main(int argc, char* argv[]){
    printf("Hello World!\n");
    return 0;
}

//void main(){
//    printf("hello\n");
//}

//main(){
//    printf("hello\n");
//}

//void print1(){
//   printf("hello in fun\n");
//}

//main(){
//   print1();
//}

C语言基本结构文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

CMake

cmake 使用 c90 标准也能通过文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

cmake_minimum_required(VERSION 3.23)
project(clangcode C)

set(CMAKE_C_STANDARD 90)

add_executable(clangcode hello.c)

C语言基本结构文章源自浅海拾贝-https://blog.terwergreen.com/c-language-basic-structure-1my3ua.html

相关文章
  • 扫码加我微信
  • 验证消息请输入:来自你的博客
  • weinxin
  • 我的微信公众号
  • 微信扫一扫与我交流吧
  • weinxin
Terwer
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: