07 C Another

标签和goto语句

标签语法:LABEL:Stmt

goto语句语法:goto LABEL;

#include <stdio.h>
int main()
{
    int n = 100;
  loop:  
    if (n <= 200)
    {
        printf("%6d", n);
        n += 1;
        goto loop;
    }
    return 0;
}
//goto语句尽量不用

ctype.h 函数

字符测试函数 字符映射函数
isalpha() 字母 tolower() 返回小写
isdigit() 数字 toupper() 返回大写

统计单词

#include <stdio.h>
#include <ctype.h>         // for isspace()
#include <stdbool.h>       // for bool, true, false
#define STOP '|'
int main(void)
{
    char c;                 // read in character
    char prev;              // previous character read
    long n_chars = 0L;      // number of characters
    int n_lines = 0;        // number of lines
    int n_words = 0;        // number of words
    int p_lines = 0;        // number of partial lines
    bool inword = false;    // == true if c is in a word

    printf("Enter text to be analyzed (| to terminate):\n");
    prev = '\n';            // used to identify complete lines
    while ((c = getchar()) != STOP)
    {
        n_chars++;          // count characters
        if (c == '\n')
            n_lines++;      // count lines
        if (!isspace(c) && !inword)
        {
            inword = true;  // starting a new word
            n_words++;      // count word
        }
        if (isspace(c) && inword)
            inword = false; // reached end of word
        prev = c;           // save character value
    }

    if (prev != '\n')
        p_lines = 1;
    printf("characters = %ld, words = %d, lines = %d, ",
           n_chars, n_words, n_lines);
    printf("partial lines = %d\n", p_lines);

    return 0;
}

编译预处理

宏定义 #define

#define 宏名 [宏体]

宏名为标识符,宏体为任意文本

//宏定义不改变字符串常量的值
#define PI 3.1415
printf("PI=%f\n",PI);
//宏定义可嵌套不可递归
#define A 1
#define B A+1//right
#define N N+2//wrong
//要使用必要的括号
#define W 80
#define L W+40
printf("%d",L*2);//结果为160不是240
//correct:#define L (W+40)

带参数的宏定义

#define 宏名(形参列表) 宏体

#define AERA(a,b) a*b//宏名(形参列表)中不能有空格
int area=AREA(3,2);
//int area=3*2;

取消宏定义

#undef 宏名 终止宏名的作用域

实现函数功能

#define MAX(x,y) ((x)>(y)?(x):(y))
int a=1,b=2;
printf("%d",MAX(a+1,b*2));

文件包含 #include

#include “文件名”

使用双引号时,先在当前目录搜索,再去标准库的头文件目录

#include <文件名>

使用尖括号时,直接在标准库的头文件目录搜索

条件编译 #if-#else-#endif

#if expression
	section1
[#else
	section2]
#endif

多文件编译

包含多个源代码文件,先逐个编译再链接

main.c

#include <stdio.h>
#include "mylib.h"
int main()
{
    printf("%d\n",add(1,2));
    return 0;
}
#include "mylib.h"

mylib.h

#ifndf ABC//避免被多次包含
#define ABC
int add(int x,int n);
int g;
#endif

mylib.c

int add(int a,int b)
{
	return a+b;
}
posted @ 2025-04-11 16:22  YamadaRyou  阅读(16)  评论(0)    收藏  举报