Empty controlled statement found как исправить

Как я могу гарантировать, что следующий оператор if, else if соответствует следующему правилу: "Если все в либо /*Condition 1*/, либо /*Condition 2*/ верно, тогда продолжайте оценивать /*Conditions 3 - 12*/ " В настоящее время я получаю сообщение об ошибке / предупреждении компилятора empt....

Как я могу гарантировать, что следующий оператор if, else if соответствует следующему правилу:

«Если все в либо /*Condition 1*/, либо /*Condition 2*/ верно,
тогда
продолжайте оценивать /*Conditions 3 - 12*/ «

В настоящее время я получаю сообщение об ошибке / предупреждении компилятора empty controlled statement found 313 38 .

if(shiftOneClose < shiftOneOpen){ /*Condition 1*/
   if((bearHammer / (shiftOneOpen - shiftOneLow) <= OoTMax))
   if((bearHammer / bullNail) <= OoTMax)
   if(bearHammer >= Transform(PCM,2)); /*Line 313*/

}

else if(shiftOneClose > shiftOneOpen){ /*Condition 2*/
   if((bullHammer / (shiftOneClose - shiftOneLow) <= OoTMax))
   if((bullHammer / bullNail) <= OoTMax)
   if(bullHammer >= Transform(PCM,2));

}

if.... /*Conditions 3 - 12*/
if....
if....
if....
if....
if....
if....
if....
if....
if....
{

  [execute trade]

}

2 ответа

Лучший ответ

Вы можете использовать общие управляющие структуры, за которыми следуют другие языки программирования, такие как C ++, JAVA.

Если вы не знакомы:
&& обозначает and
|| это означает or

Примере:

//--- so in order to make it evaluate conditions 3-12, if only condition 1 or 2 is true
if(condition1 || condition2){
  if(condition3 && condition4){ /* so on until 12 */
     //--- execute trade
  }
}

Чтобы улучшить читаемость кода, я предлагаю вам перенести некоторые условия в функции


0

TheLastStark
9 Ноя 2020 в 07:47

Q : «Как мне убедиться, что следующий оператор if, else if соответствует следующему правилу:
«Если все в /*Condition 1*/ или /*Condition 2*/ верно,
тогда продолжайте оценку /*Conditions 3 - 12*/» «

Исходный код взорвался в line 313 , потому что ; -символ завершает оператор-конструктор, в то время как нечего «выполнять», если (любое) из if(){...}else{...} — ed условий было выполнено (та же проблема есть в части else{...}, где также нет ни одного {...} — кодовый блок присутствует, и конструктор формального оператора получает паника, не зная, что «выполнить» в любой из ветвей if(){...}else{...}, поскольку утверждение формально не завершено).

    if (  shiftOneClose < shiftOneOpen )                               /*Condition 1*/
    {                                                       
       if ( ( bearHammer / ( shiftOneOpen - shiftOneLow ) <= OoTMax )            )
       if ( ( bearHammer / bullNail )                     <= OoTMax              )
       if (   bearHammer                                  >= Transform( PCM, 2 ) ); /*Line 313*/

    }

Итак, не сказать, что делать, если условия будут выполнены, — это основная проблема, о которой говорилось выше.


Решение для части «КАК Я БУДЕТ ОБЕСПЕЧИТЬ …» :

Синтаксически правильным был бы этот пояснительный шаблон кода, сохраняющий логику:

if (  (  (  shiftOneClose       <    shiftOneOpen
         && OoTMax              >= ( bearHammer / ( shiftOneOpen - shiftOneLow ) )
         && OoTMax              >= ( bearHammer / bullNail                       )
         && Transform( PCM, 2 ) <=   bearHammer
            ) /*--------------------------------------------------------------------- Condition 1 */
      || (  shiftOneClose       >    shiftOneOpen
         && OoTMax              >= ( bullHammer / ( shiftOneClose - shiftOneLow ) )
         && OoTMax              >= ( bullHammer / bullNail                        )
         && Transform( PCM, 2 ) <=   bullHammer
            ) /*---------------------------------------------------------------- .OR. Condition 2 */
         )
   && ( ... ) /*---------------------------------------------------------------- .AND.Condition 3 */
   && ( ... ) /*---------------------------------------------------------------- .AND.Condition 4 */
   && ( ... ) /*---------------------------------------------------------------- .AND.Condition 5 */
   && ( ... ) /*---------------------------------------------------------------- .AND.Condition 6 */
   && ( ... ) /*---------------------------------------------------------------- .AND.Condition 7 */
   && ( ... ) /*---------------------------------------------------------------- .AND.Condition 8 */
   && ( ... ) /*---------------------------------------------------------------- .AND.Condition 9 */
   && ( ... ) /*---------------------------------------------------------------- .AND.Condition A */
   && ( ... ) /*---------------------------------------------------------------- .AND.Condition B */
      )
   {...} /*---------------------------------- CODE-BLOCK TO EXECUTE ------------------------------*/

За мои ~ 20 с лишним лет квантового моделирования мы всегда предпочитали широкоформатную компоновку (экраны дешевы, а многоэкранные сиденья 4 x 2 и больше — это просто и так распространено более чем в последнее десятилетие), акцент на логики, затем уменьшая дублирование в вычислениях (лучше всего предварительно вычислять любую и всю логику — «контрольные значения», которые затем будут повторно использоваться, и из-за причин низкой задержки (часто сверхнизкой задержки) мы никогда не прибегал к тому, чтобы тратить дополнительное время на вызов функции (накладные расходы с переключением контекста и передачей параметров туда и обратно). Не все компиляторы (версии) сокращали ветви выполнения из-за законов логики, поэтому необходимо соблюдать осторожность взяты здесь (самые дорогие функции — это те, которые манипулируют / запрашивают db.POOL — хранилище с данными сделок, с ужасно дорогими затратами, связанными с необходимостью сначала выполнять манипуляции с указателем db.POOL, а затем и только потом ( в случае успеха и никогда иначе) повторно получить доступ к db.POOL — элементам данных записи).

Также следует заметить, что существует логическая слепая зона — shiftOneClose == shiftOneOpen.


0

user3666197
9 Ноя 2020 в 13:15

  • Forum
  • Beginners
  • Empty controlled statement error.

Empty controlled statement error.

Getting this warning ’empty controlled statement found’
I can normally spot these, but in this case I cannot.
Here is a portion of the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
template < class T >
int movement (vector<T> &genvector) 
{

//other code
 int usePts = 0;
  cout<<"Enter Order.n";
  cin >> usePts;
				 
	 int ordertot = genvector[chain].orders;  //vector of objects passed into template function

	    if(usePts > ordertot);
			 {
	    		cout<<" Insufficient orders.n"; 
			 }

		 if(usePts <= ordertot); //this being line 1410 referred to  
			 {
			   genvector[chain].giveorders (-usePts);  
			   moday = (usePts*2); //this is part of other code.
			 }

 return 0;
 }


//error = (1410): warning C4390: ';' : empty controlled statement found; is this the intent? 

Last edited on

The problem is the ; in

The ; reprisent the {} of the if-statement and the {} below that are ignored becouse they
are not preceded by a command

And by that I mean the {} are ignored and the commands within are always executed.

The same is true for line 12 (1405 in your program).

Last edited on

Thanks Thenero.
I cannot believe i couldnt spot such a basic error. I am a moron.
Thanks again.

Topic archived. No new replies allowed.

  1. 07-21-2002


    #1

    empty control statement (?)

    I have a program. Here is the code that is giving me a warning:

    Code:

    void Sensor::SetSensorState(char *cState) {
    	char On[] = "On";
    	char Off[] = "Off";
    	
    	if(!strcmp(cState, On));
    		strncpy(State, cState, 50);*
    	if(!strcmp(cState, Off));
    		strncpy(State, cState, 50);*
    	
    }

    On the lines with the ‘*’ I am getting a warning that says :

    warning C4390: ‘;’ : empty controlled statement found; is this the intent?

    as I said this is a warning, not an error, so my program compiles and runs (up to this point).
    what should I change about the code above?

    [edit]
    nevermind….duh…that was a lame mistake…


  2. 07-21-2002


    #2

    The Dog is offline


    Registered User

    The Dog's Avatar


    Remove the ‘;’ after the if.


  3. 07-21-2002


    #3

    are you making fun of me?


  4. 07-21-2002


    #4

    endo is offline


    Seeking motivation…

    endo's Avatar


    No he isn’t, if statements dont have ;’s at the end like other control structures.

    while( condition ) //no ;
    {

    }

    for( initialise; end condition; increment ) //no ;
    {

    }

    if( condition ) //no ;
    {

    }


  5. 08-05-2002


    #5

    It is perfect legally to put «;» after if, thenyou got a warning.

    what are you trying to do though?

    what do I know?


  6. 08-05-2002


    #6

    MrWizard is offline


    Registered User


    Originally posted by Unregistered
    It is perfect legally to put «;» after if, thenyou got a warning.

    what are you trying to do though?

    what do I know?

    Of course its perfectly legal, but just because something is legal doesn’t mean that is always what we want. For instance these two statements are the same and do nothing.

    Code:

    // Statement 1
    if( bValue == true );
    
    // Statement 2
    if( bValue == true )
      ;

    Both do nothing because there are no brackets, it will only execute the first command after the if statement, which is a nothing, just the semi-colon. That’s why if you do this on a for loop it just runs the entire loop without going inside of it.

    «…the results are undefined, and we all know what «undefined» means: it means it works during development, it works during testing, and it blows up in your most important customers’ faces.» —Scott Meyers


  • Remove From My Forums
  • Question

  • I wrote a code in VS10 C++ and I can’t understand the error messages… Please I need help…

    /* Declare Libraries Used Here */
    
    
    
    #include <iostream>			 // Input/Output Library
    
    
    
    
    
    
    
    using namespace std;
    
    
    
    //-------------------------------------------------------------------
    
    
    
    // Main Function - Program Begins Here
    
    
    
    int main()
    
    
    
    {
    
    
    
    	// Variable Declaration
    
    
    
    	int up = 0, low = 0, other = 0, count = 5;
    
    
    
    	char input;
    
    
    
    
    
    
    
    	// Loop For Entering Characters And Count Inputs
    
    
    
    	while(count > 0)
    
    
    
    	{
    
    
    
    		cout << "Enter a character: ";
    
    
    
    		cin >> input;
    
    
    
    		if (input >= 'A') && (input <= 'z')
    
    
    
    		{
    
    
    
    			if (input >= 'A') && (input <= 'Z')
    
    
    
    			{
    
    
    
    				up ++;
    
    
    
    			}
    
    
    
    			else if (input >= '[') && (input <= '`')
    
    
    
    			{
    
    
    
    				other ++;
    
    
    
    			}
    
    
    
    			else if (input >= 'a') && (input <= 'z')
    
    
    
    			{
    
    
    
    				low ++;
    
    
    
    			}
    
    
    
    			count--;
    
    
    
    		}
    
    
    
    		else
    
    
    
    		{
    
    
    
    			cout << "Wrong Input";
    
    
    
    		}
    
    
    
    	}
    
    
    
    
    
    
    
    	cout << "Uppecase Characters: " << up << endl;
    
    
    
    	cout << "Lowercase Characters: " << low << endl;
    
    
    
    	cout << "Other Characters: " << other << endl;
    
    
    
    
    
    
    
    	// Press Any Key To Continue
    
    
    
    	system("pause");
    
    
    
    	return 0;
    
    
    
    }
    
    
    
    //-------------------------------------------------------------------
    
    
    
    

    This is a list of the errors and warnings I got:

    Error 1 error C2143: syntax error : missing ‘;’ before ‘&&’

    Warning 2 warning C4390: ‘;’ : empty controlled statement found; is this the intent?

    Error 3 error C2143: syntax error : missing ‘;’ before ‘{‘

    Error 4 error C2143: syntax error : missing ‘;’ before ‘&&’

    Warning 5 warning C4390: ‘;’ : empty controlled statement found; is this the intent?

    Error 6 error C2143: syntax error : missing ‘;’ before ‘{‘

    Error 7 error C2181: illegal else without matching if

    Error 8 error C2143: syntax error : missing ‘;’ before ‘&&’

    Warning 9 warning C4390: ‘;’ : empty controlled statement found; is this the intent?

    Error 10 error C2143: syntax error : missing ‘;’ before ‘{‘

    Error 11 error C2181: illegal else without matching if

    Error 12 error C2143: syntax error : missing ‘;’ before ‘&&’

    Warning 13 warning C4390: ‘;’ : empty controlled statement found; is this the intent?

    Error 14 error C2143: syntax error : missing ‘;’ before ‘{‘

    Error 15 error C2181: illegal else without matching if

     16 IntelliSense: expected an expression

     17 IntelliSense: expected a ‘;’

    • Edited by

      Friday, January 21, 2011 2:00 PM

Answers

  • The condition(s) to be tested in an if statement
    need to be in parentheses:

    if( (input >= ‘A’) && (input <= ‘z’) )

    or

    if (input >= ‘A’ && input <= ‘z’)

    — Wayne

    • Marked as answer by
      Pambos Christofi
      Friday, January 21, 2011 4:49 PM

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Empires and puzzles ошибка входа
  • Empires and puzzles как изменить построение команды обороны
  • Empire total war унизительный договор как исправить
  • Empire total war как изменить форму правления
  • Empire total war как изменить количество юнитов

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии