c primer plus 專題7:分支和跳轉

1 if 語句

#include <stdio.h>

int main(void)
{
	const int FREEZING = 0;
	float temperature;
	int cool_days = 0;
	int all_days = 0;

	printf("Enter the list of daily low temperatures.\n");
	printf("Use Celsius, and enter q to quit.\n");
	while (scanf("%f", &temperature) == 1)
	{
		all_days++;
		if (temperature < FREEZING)
			cool_days++;
	}
	if (all_days != 0)
		printf("%d days total: %.1f%% were below freezing.\n",
			all_days, 100.0 * cool_days / all_days);
	else
		printf("No data entered!\n");

	return 0;
}

2 字符輸入函數

getchar() 和 putchar()

#include <stdio.h>
#define SPACE	' '
int main(void)
{
	char ch;

	printf("Enter string:\n");
	while ((ch = getchar()) != '\n')
	{
		if (ch == SPACE)
			putchar(ch);
		else
			putchar(ch + 1);
	}
	printf("\nDone!\n");

	return 0;
}

執行結果如下

3 多重選擇

if (expression)
	statement
else if (expression)
	statement
else if (expression)
	statement
else 
	statement

注意,if else 總是與最近的語句相匹配。

4 邏輯運算符

優先級(非常重要):! > 算術運算符 > 關係運算符 > 邏輯運算符 > 賦值運算符。

5 條件運算符

利用條件運算符,處理單複數的問題:

printf("You need %d %s of paint.\n", cans,
    cans == 1 ? "can" : "cans");

這裏,利用條件運算符,來給字符串賦值(單複數)。

6 循環輔助 

1 continue 語句

使用 continue 的好處:可以減少程序的縮進。

如下所示:
 

2 break 語句(僅跳出當前層的循環)

比較 break 和 continue 語句

使用 break 的實例

#include <stdio.h>

int main(void)
{
	float length, width;

	printf("Enter the length of rectangle: \n");
	while (scanf("%f", &length) == 1)
	{
		printf("Length = %.2f:\n", length);
		printf("Enter its width:\n");
		if (scanf("%f", &width) != 1)
			break;
		printf("Width = %.2f:\n", width);
		printf("Area = %.2f:\n", length * width);
		printf("Enter the length of rectangle: \n");
	}
	printf("All done, exit!!!\n");

	return 0;
}

7 多重選擇

swtich case 語句

帶多重選擇的 switch 語句

#include <stdio.h>

int main(void)
{
	char ch;
	int a_cnt, e_cnt, i_cnt, o_cnt, u_cnt;

	a_cnt = e_cnt = i_cnt = o_cnt = u_cnt = 0;
	
	printf("Enter some text, enter # to quit.\n");
	while ((ch = getchar()) != '#')
	{
		switch (ch)
		{
			case 'a':
			case 'A': a_cnt++;
				break;
			case 'e':
			case 'E': e_cnt++;
				break;
			case 'i':
			case 'I': i_cnt++;
				break;
			case 'o':
			case 'O': o_cnt++;
				break;
			case 'u':
			case 'U': u_cnt++;
				break;
			default:
				break;
		}
	}
	printf("total numbers:   A    E    I    O    U\n");
	printf("              %4d %4d %4d %4d %4d\n", a_cnt, e_cnt, i_cnt, o_cnt, u_cnt);
	printf("All done, exit!!!\n");

	return 0;
}

8 goto

c語言的goto語句:

goto語句的常規用法(要跳轉的標籤位置在上面)

#include<stdio.h>
int main(void) 
{
	int n;
pos_1:
	printf("請輸入一個正整數:");
	scanf("%d", &n);
	if (n < 0)
	{
		printf("輸入錯誤!\n");
		goto pos_1;
	}
	printf("成功輸入正整數:%d\n", n);
	return 0;
}

很多C語言的參考書,都不提倡使用 goto 語句,下面是使用 goto 語句比較好的應用場景。

1 在I2C寫入時,通常要等待操作完成,才能繼續寫入,下面是goto的使用

int Sensors_I2C_WriteRegister(unsigned char slave_addr,
                              unsigned char reg_addr,
                              unsigned short len,
                              const unsigned char *data_ptr)
{
  char retries=0;
  int ret = 0;
  unsigned short retry_in_mlsec = Get_I2C_Retry();

tryWriteAgain:
  ret = 0;
  ret = ST_Sensors_I2C_WriteRegister( slave_addr, reg_addr, len, ( unsigned char *)data_ptr);

  if(ret && retry_in_mlsec)
  {
    if( retries++ > 4 )
        return ret;

    mdelay(retry_in_mlsec);
    goto tryWriteAgain;
  }
  return ret;
}

上述程序,利用 goto 語句,嘗試多次寫入I2C。若 4 次仍失敗,則退出。

2 函數內部使用(統一出口)

int getresult_use_goto()
{
    int iResult = 0;
 
    FILE*    fp1 = NULL;
    FILE*    fp2 = NULL;
    char*    pMem1 = NULL;
    char*    pMem2 = NULL;
     
    fp1 = fopen("C:\\file1", "rb");
    if (NULL == fp1)  goto End;
 
    fp2 = fopen("C:\\file2", "rb");
    if (NULL == fp2)  goto End;
 
    pMem1 = (char *)malloc(1000);
    if (NULL == pMem1) goto End;
 
    pMem2 = (char *)malloc(2000);
    if (NULL == pMem2) goto End;
 
    iResult = 1;
 
End:
    if (fp1) fclose(fp1);
    if (fp2) fclose(fp2);
    if (pMem1) free(pMem1);
    if (pMem2) free(pMem2);
    return iResult;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章