"Play through the corners of embedded C" When you need the loop body to execute at least once, choose do

CSDN Blog Homepage
ID: Eterlove
, one stroke at a time, recording my study life! Standing on Shoulders
of Giants!

This article is original, please indicate the source and author for reprinting!

When you need the loop body to be executed at least once, choose do-----《C and Pointers》

1. Concept

       Usually, we often use the while statement to express our idea of ​​" judging first and then looping ". In addition, the while statement has a brother called do statement, or do-while. His distinctive feature is " looping first and then judging ", which will be executed at least once loop body.
The syntax of do is:

do{
    
    
      statement   //为循环体
}while(expresssion);  //expresssion测试表达式,其值为1或0

2. The execution process of the do statement

insert image description here
When to use a do-while statement instead of a while() statement?
When you need the loop body to execute at least once, choose do

3. Please remember to bring it;

       I want to emphasize that many people who are not in the habit of using do-while statements often make a low-level mistake when they have to use do-while statements to deal with problems -- forgetting an important point No. while(expression);

This do-while statement is often used in the process of MCU USART debugging and sending data

void usart_SendString(u8 *str)
{
    
    
	u8 index=0;
	do
	{
    
    
		USART_SendData(USART2,str[index]);				//发送数据
		while(USART_GetFlagStatus(USART2,USART_FLAG_TXE)==RESET);
		//若数据没有发送完成,则会死在while语句里面!
		index++;
	}while(str[index] != 0);						//检查字符串结束标志
}
	while(USART_GetFlagStatus(USART2,USART_FLAG_TXE)==RESET);
	//其他人还偏爱于另一种写法:
	while(!USART_GetFlagStatus(USART2,USART_FLAG_TXE));

Guess you like

Origin blog.csdn.net/Eterlove/article/details/122672628