Содержание
- C# Preprocessor bug?; found in VS2017 (15.7.2) #27109
- Comments
- #if preprocessor directive incorrectly handles enclosed C# verbatim string #4726
- Comments
- Main cs 2 0 error cs1024 wrong preprocessor directive
C# Preprocessor bug?; found in VS2017 (15.7.2) #27109
The code below gives the following compilation error:
error CS1024: Preprocessor directive expected
The strange part is that it ONLY happens when the code is part of a #if/#endif block that is NOT defined.
This seems like a bug.
The text was updated successfully, but these errors were encountered:
This is not a bug and is very much the design of C# since v1. 🙂
When _THIS_IS_NOT_DEFINED_ is not defined, then the compiler gets to the #if , sees that the condition is false, and considers all text up to the next preprocessor directive (like #else , #elif or #endif ) as ‘disabled text’. In this case, this means it just consumes the code blindly as text until it sees teh # in #rates . There, it says «aha, what sort of directive do i have? ‘rates’?? that’s not a thing. ERROR!».
The difference here is that when the scanner is dealing with ‘disabled text’ sections, it’s not going and making tokens like the normal scanning does. So it has no concept that @» is special and starts some sort of string. Instead, it just does not give a hoot.
** This is important as you want people to put any code they want into a verbatim string (except a quote) and not have the compiler ‘interpret’ it in any fashion. Otherwise, you’d have to escape your pp-directives in a string, which would defeat the purpose of it being a ‘verbatim’ string. 🙂
Thanks for the detail explanation. It does feel odd that valid code can start to fail if wrapped in an undefined preprocessor block in this way; however, it is certainly easy to work around. Should the scanning of disabled text take into account the @» text as a future improvement to the C# preprocessor? I’m just curious on your take.
text take into account the @» text as a future improvement to the C# preprocessor? I’m just curious on your take.
Unfortunately, that can’t happen, it would be a breaking change. There is code out there that def depends on this behavior. :-/
Maybe it would make sense to ignore unknown preprocessor directives in disabled sections of code? I think that wouldn’t be a breaking change.
Источник
#if preprocessor directive incorrectly handles enclosed C# verbatim string #4726
To reproduce, just use this code and make sure that DEBUG is set:
Actually, this produces a CS1024 error because the compiler seems to interpret the «# text» portion of the string as a preprocessor directive.
The text was updated successfully, but these errors were encountered:
I’m pretty sure this is by design. Once the compiler sees the #if !DEBUG it’s going to be in an inactive region. Once in that state it will continue scanning through the inactive region handling other preprocessor directives, until it finally ends that region (with the #endif ). Inside that region, the compiler has no concept of things a multi-line string literal.
We should investigate whether this is a bug or per spec.
From my reading, this is ‘per spec’. The relevant sections are:
Because ‘DEBUG’ is defined, then the pp-expression evaluates to false , meaning we’ll be in a skipped-section .
The spec then says:
The remaining conditional-sections, if any, are processed as skipped-sections: except for pre-processing directives, the source code in the section need not adhere to the lexical grammar; no tokens are generated from the source code in the section; and pre-processing directives in the section must be lexically correct but are not otherwise processed.
As such, it is ‘per spec’ that an error is produced as the compiler is checking that the #text «pre-processing directives in the section must be lexically correct». As #text is not a legal pp-directive, the error is appropriate.
Fair enough; per the spec I agree that this can’t be considered a bug. Nonetheless it is rather unintuitive behavior — requiring pre-processing directives to be «lexically correct» while declaring that they are unprocessed goes contrary to what one would expect — that everything is skipped until the #endif directive is encountered at the beginning of a line. Sounds like my problem is actually with the spec and not the implementation 🙂
All that being said, this was a rather odd scenario that popped up and was easy to work around. Thanks for looking into it.
When commenting out a block of code, I recommend using line-ending comments. In VS, select the code to be commented out and hit control-K control-C. To uncomment a block of code select it and hit control-K control-U.
I acknowledge that this doesn’t help in your scenario, where you want the code commented or not depending on a PP-symbol.
Agreed on the line-ending comments; I’m a big fan of ctrl-K,C. This was literally a case of production code having a C# verbatim string inside a skipped block with a line that happened to begin with #. I can’t imagine that this is a very common use case, but I wanted to at least report this behavior in case it wasn’t intended. Again, thanks for taking the time to check this out and explain it to me.
I think it’s so you don’t end up accident writing something like:
in the middle of your skipped section. With the current spec approach, you’ll get a nice error here and you can fix the directive.
From: gdivismailto:notifications@github.com
Sent: 8/24/2015 10:21 AM
To: dotnet/roslynmailto:roslyn@noreply.github.com
Cc: Cyrus Najmabadimailto:cyrusn@microsoft.com
Subject: Re: [roslyn] #if preprocessor directive incorrectly handles enclosed C# verbatim string (#4726)
Fair enough; per the spec I agree that this can’t be considered a bug. Nonetheless it is rather unintuitive behavior — requiring pre-processing directives to be «lexically correct» while declaring that they are unprocessed goes contrary to what one would expect — that everything is skipped until the #endif directive is encountered at the beginning of a line. Sounds like my problem is actually with the spec and not the implementation 🙂
All that being said, this was a rather odd scenario that popped up and was easy to work around. Thanks for looking into it.
Источник
Main cs 2 0 error cs1024 wrong preprocessor directive
В стандарте написано следующее:
9.5.4 Conditional compilation directives
.
The remaining conditional-sections, if any, are processed as skipped-sections: except for pre-processing
directives, the source code in the section need not adhere to the lexical grammar; no tokens are generated
from the source code in the section; and pre-processing directives in the section shall be lexically correct but
are not otherwise processed.
|
От: | Ovl |
Дата: | 01.06.07 14:01 | |
Оценка: |
N>9.5.4 Conditional compilation directives
N>.
N>The remaining conditional-sections, if any, are processed as skipped-sections: except for pre-processing
N>directives, the source code in the section need not adhere to the lexical grammar; no tokens are generated
N>from the source code in the section; and pre-processing directives in the section shall be lexically correct but
N>are not otherwise processed.
|
От: | Ovl |
Дата: | 01.06.07 14:02 | |
Оценка: |
|
От: | Ovl |
Дата: | 01.06.07 14:06 | |
Оценка: |
Здравствуйте, Ovl, Вы писали:
Ovl>хотя да, даже валидный #if не пропускается. странные коментарии в с#
а, ну да. он же не валиден
вот так все в порядке
|
От: | lonli |
Дата: | 01.06.07 14:59 | |
Оценка: |
Здравствуйте, nikov, Вы писали:
Да забей ты
«Чтобы все знать интернет нафик не нужен! НУжен утюг!» ©сб. БГУ
|
От: | Алексей. |
Дата: | 04.06.07 07:58 | |
Оценка: |
N>9.5.4 Conditional compilation directives
N>.
N>The remaining conditional-sections, if any, are processed as skipped-sections: except for pre-processing
N>directives, the source code in the section need not adhere to the lexical grammar; no tokens are generated
N>from the source code in the section; and pre-processing directives in the section shall be lexically correct but
N>are not otherwise processed.
|
От: | nikov | http://www.linkedin.com/in/nikov |
Дата: | 04.06.07 08:03 | ||
Оценка: |
Здравствуйте, Алексей., Вы писали:
А>Компилятор в данном случае соотвествует стандарту. Многострочный комментарий, тот что со звездочками, не имеет эффект в skipped-секциях и обрабатывается как последовательность входных символов, а не как единый токен-комментарий. Поэтому когда компилятор встречает #bugaga внутри skipped-секции он его пытается обработать как директиву препроцессора.
Про комментарии я понимаю. Но в стандарте написано, что директивы препроцессора в skipped-секции не обрабатываются, если они не являются лексически корректными. Иначе получилось бы, что текст внутри skipped-секции, случайно начинающийся с #, будет вызывать ошибку (что мы и наблюдаем).
|
От: | Алексей. |
Дата: | 04.06.07 08:19 | |
Оценка: |
Здравствуйте, nikov, Вы писали:
N>Про комментарии я понимаю. Но в стандарте написано, что директивы препроцессора в skipped-секции не обрабатываются, если они не являются лексически корректными. Иначе получилось бы, что текст внутри skipped-секции, случайно начинающийся с #, будет вызывать ошибку (что мы и наблюдаем).
Хм. Похоже ты прав. Невнимательно я прочитал выделенную фразу.
|
От: | Ovl |
Дата: | 04.06.07 08:32 | |
Оценка: |
Здравствуйте, nikov, Вы писали:
N>Здравствуйте, Алексей., Вы писали:
А>>Компилятор в данном случае соотвествует стандарту. Многострочный комментарий, тот что со звездочками, не имеет эффект в skipped-секциях и обрабатывается как последовательность входных символов, а не как единый токен-комментарий. Поэтому когда компилятор встречает #bugaga внутри skipped-секции он его пытается обработать как директиву препроцессора.
N>Про комментарии я понимаю. Но в стандарте написано, что директивы препроцессора в skipped-секции не обрабатываются, если они не являются лексически корректными. Иначе получилось бы, что текст внутри skipped-секции, случайно начинающийся с #, будет вызывать ошибку (что мы и наблюдаем).
простите, а как вы перевели фразу?
except for pre-processing directives, the source code in the section need not adhere to the lexical grammar
and pre-processing directives in the section shall be lexically correct but are not otherwise processed
|
От: | nikov | http://www.linkedin.com/in/nikov |
Дата: | 04.06.07 09:44 | ||
Оценка: | -1 |
except for pre-processing directives, the source code in the section need not adhere to the lexical grammar
код в этой секции, за исключением директив препроцессора, не обязан придерживаться [правил] грамматики
and pre-processing dirctives in the section shall be lexically correct but are not otherwise processed
директивам препроцессора в этой секции следует быть лексически правильными, иначе они не будут обработаны
|
От: | Ovl |
Дата: | 04.06.07 09:46 | |
Оценка: | 23 (2) |
except for pre-processing directives, the source code in the section need not adhere to the lexical grammar
код в этой секции, за исключением директив препроцессора, не обязан придерживаться [правил] грамматики
and pre-processing dirctives in the section shall be lexically correct but are not otherwise processed
директивам препроцессора в этой секции следует быть лексически правильными, иначе они не будут обработаны
|
От: | nikov | http://www.linkedin.com/in/nikov |
Дата: | 04.06.07 09:50 | ||
Оценка: |
директивам препроцессора в этой секции следует быть лексически правильными, иначе они не будут обработаны
Ovl>директивам препроцессора в этой секции следует быть лексически правильными, кроме этого они никак не обработываются
Спасибо, я согласен. Мой перевод был неверным.
Однако, #bugaga — это не директива препроцессора, и она не обязана быть лексически правильной.
|
От: | Ovl |
Дата: | 04.06.07 09:53 | |
Оценка: |
N>Однако, #bugaga — это не директива препроцессора, и она не обязана быть лексически правильной.
директива — это последовательность # если перед ним до начала строки ничего нет
|
От: | nikov | http://www.linkedin.com/in/nikov |
Дата: | 04.06.07 09:55 | ||
Оценка: |
Здравствуйте, Ovl, Вы писали:
N>>Однако, #bugaga — это не директива препроцессора, и она не обязана быть лексически правильной.
Ovl>директива — это последовательность # если перед ним до начала строки ничего нет
Откуда это следует?
Я ориентируюсь на следующее определение:
|
От: | Алексей. |
Дата: | 04.06.07 10:00 | |
Оценка: |
and pre-processing dirctives in the section shall be lexically correct but are not otherwise processed
директивам препроцессора в этой секции следует быть лексически правильными, иначе они не будут обработаны
Ovl>директивам препроцессора в этой секции следует быть лексически правильными, кроме этого они никак не обработываются
Спасибо за перевод. Значит компилятор и я все-таки правы.
|
От: | nikov | http://www.linkedin.com/in/nikov |
Дата: | 04.06.07 10:09 | ||
Оценка: |
Здравствуйте, Ovl, Вы писали:
Ovl>директива — это последовательность # если перед ним до начала строки ничего нет
Компилятор выдает ошибку и на таком коде:
, где никакого слова нет.
|
От: | Ovl |
Дата: | 04.06.07 10:12 | |
Оценка: |
Здравствуйте, nikov, Вы писали:
N>Здравствуйте, Ovl, Вы писали:
N>>>Однако, #bugaga — это не директива препроцессора, и она не обязана быть лексически правильной.
Ovl>>директива — это последовательность # если перед ним до начала строки ничего нет
N>Откуда это следует?
N>Я ориентируюсь на следующее определение:
N>
верно. это правильные директивы.
а списка неправильных там разве не приведено?
A pre-processing directive always occupies a separate line of source code and always begins
with a # character and a pre-processing directive name. White space may occur before the # character
and between the # character and the directive name.
|
От: | nikov | http://www.linkedin.com/in/nikov |
Дата: | 04.06.07 10:14 | ||
Оценка: |
Ovl>A pre-processing directive always occupies a separate line of source code and always begins
Ovl>with a # character and a pre-processing directive name. White space may occur before the # character
Ovl>and between the # character and the directive name.
|
От: | Ovl |
Дата: | 04.06.07 10:19 | |
Оценка: |
Здравствуйте, nikov, Вы писали:
N>Здравствуйте, Ovl, Вы писали:
Ovl>>директива — это последовательность # если перед ним до начала строки ничего нет
N>Компилятор выдает ошибку и на таком коде:
N>
N>, где никакого слова нет.
нету. об этом вам компилятор и говорит. что-нибудь типа «directive expected»
|
От: | nikov | http://www.linkedin.com/in/nikov |
Дата: | 04.06.07 11:02 | ||
Оценка: |
Здравствуйте, Ovl, Вы писали:
Ovl>нету. об этом вам компилятор и говорит. что-нибудь типа «directive expected»
В общем, ситуация понятна. Если внутри skipped-секции встречается строка, первый непробельный символ в которой — #, то эта строка должна содержать корректную директиву препроцессора, иначе возникает ошибка компиляции. Я бы не сказал, что эта мысль ясно выражена в стандарте.
Источник
This is not a bug and is very much the design of C# since v1.
When _THIS_IS_NOT_DEFINED_
is not defined, then the compiler gets to the #if
, sees that the condition is false, and considers all text up to the next preprocessor directive (like #else
, #elif
or #endif
) as ‘disabled text’. In this case, this means it just consumes the code blindly as text until it sees teh #
in #rates
. There, it says «aha, what sort of directive do i have? ‘rates’?? that’s not a thing. ERROR!».
Now, in the case where _THIS_IS_NOT_DEFINED_
is defined, then the compiler says: what follows is totally normal code that i will scan (i.e. ‘lex’) into tokens. In this case, it gets tokens like class
Class
{
, etc. It eventually gets to the verbatim string literal and starts scanning it as a normal verbatim string. Verbatim strings consume their contents until the trailing quote is found**. So, in this case, the #rates
are just characters in that string and everything is hunky dory.
The difference here is that when the scanner is dealing with ‘disabled text’ sections, it’s not going and making tokens like the normal scanning does. So it has no concept that @"
is special and starts some sort of string. Instead, it just does not give a hoot.
—
** This is important as you want people to put any code they want into a verbatim string (except a quote) and not have the compiler ‘interpret’ it in any fashion. Otherwise, you’d have to escape your pp-directives in a string, which would defeat the purpose of it being a ‘verbatim’ string.
I’m just trying to use MS Visual for some really simple C++ coding for school purposes. The point is I can’t even write a simple hello-world alike program.
I’ve got that error «Preprocessor expected» in line with library. Line with code looks like this: #include <iostream>
Any help with solving this (probably) minor problem is welcomed.
Here is whole code:
#include <iostream>
int main()
{
std::cout << "aogaohgo";
}
asked Oct 8, 2015 at 16:11
3
OP’s reported error message is reminiscent of a C# error message.
Testing this theory and pasting OPs C++ code into a C# console project I receive:
error CS1024: Preprocessor directive expected
As the first error.
Solution: Create a new project and make sure the selected language is C++
answered Oct 8, 2015 at 17:44
user4581301user4581301
32.5k7 gold badges32 silver badges53 bronze badges
#include
isn’t valid on it’s own.
The correct syntax is #include <filename>
.
I suggest you pick up a better Hello World tutorial
answered Oct 8, 2015 at 16:13
slaphappyslaphappy
6,8663 gold badges33 silver badges59 bronze badges
2
- Remove From My Forums
-
Question
-
User82244386 posted
<asp:Repeater ID="rptrImages" runat="server"> <HeaderTemplate> <ul id="first-carousel" class="first-and-second-carousel jcarousel-skin-tango"> </HeaderTemplate> <ItemTemplate> <li onclick="showImage('342968750.jpg')"> <img src='<% #Eval("Thum_Img","../PatientTreatmentImages/{0}") %>' width="75" height="75" alt="" runat="server" /> </li> </ItemTemplate> <FooterTemplate> </ul> </FooterTemplate> </asp:Repeater>
I need to pass dynamic value from this java script function <li onclick="showImage('342968750.jpg')"> like image control . what will be the code for this .
Thanks
Answers
-
User82244386 posted
Thanks for your reply .
Here is the solution :
<ItemTemplate> <li > <img title='<% #Eval("Image")%>' src='<% #Eval("Thum_Img","../PatientTreatmentImages/{0}") %>' width="75" height="75" alt="" runat="server" onclick="showImage(this.title)"/> </li> </ItemTemplate>
-
Marked as answer by
Thursday, October 7, 2021 12:00 AM
-
Marked as answer by