does vscode inline breakpoint support C&C++ languange? - c

#include <stdio.h>
int main() {
for (/*1*/ int i = 0; /*2*/i < 10 ; /*3*/i++) { /*4*/printf("hello\n");}
return 0;
}
it seems vscode couldn't stop on breakpoint(in comments) in for statments

I'm not sure if this is a feature commonly supported. And TBH, I'd say it's a code smell if you have a need for it. Your example is trivial, and there it's no need to know what's going on between 2 and 3. And whenever you actually DO have a need for it, then your conditions and statements in the for header are likely too complicated.
And besides, most of the breakpoints. can be easily moved to equivalent positions.
/*1*/
/*2*/ First time
for (/*1*/ int i = 0; /*2*/i < 10 ; /*3*/i++)
{
/*4*/ printf("hello\n");
/*2*/ Second time and later
}
But it's not possible to put a break between 2 and 3 without rewriting the code.
If you REALLY want this and your debugger don't support it, you can rewrite it in the following way. Change this:
for (<init>;<cond>;<inc>)
{
// Loop body
}
to this:
/*1*/
for (<init>;;)
{
/*2*/ if(!(<cond>)) break;
/*4*/ // Loop body
/*3*/ <inc>;
}
From comments:
thanks, I know that the snippets post in description is of bad coding style, mainly reason behind this question is that I couldn't format existed code and I need to debug this code of bad coding style...
I completely understand your problem, but before debugging, it's often a very good advice to try to refactor the code to debuggable code before starting to debug.
Comparing to JS
You mentioned that you were able to do this in javascript. One good thing to remember here is that javascript is an interpreted language, while C and C++ are compiled languages. The compiled code does not necessarily have a good 1 to 1 correspondence with the source code. The debugger tries it best to do a good mapping, but it may fail. Especially with heavy optimization activated.

Related

Define custom syntax "until" in C

I expect I can do something like this:
int i = 0;
until (i == 2){
printf("yes\n");
i++;
}
Without telling detail about what until does, I'm sure reader know what is the algorithm from code above. Yes I know I can just use while(!condition){}.
The output will be:
yes
yes
So is it possible that I can achieve my goal?
I feel macro able to do this with define or something else. But I'm lack of knowledge about preprocessing directive syntax in C
#define until <what should I fill here>
Edit:
Many people triggered from what am I doing. I'm sorry for if I bother you guys. Don't worry, this syntax is just for my self only. So I hope I don't bother code reader who accidentally read my code or C priest.
First of all, and I can't stress this enough: making your own secret, private language using function-like macros is a cardinal sin in C. It is perhaps the worst thing you can ever do.
Why? Because other people reading your code are expected to know C. They are however not expected to know your secret private macro language. Furthermore, they have absolutely no interest in learning your secret private macro language.
So please never do things like this in real programs.
That being said, you pretty much already answered the question yourself:
#define until(condition) while(!(condition))
Note that condition, being a function-like macro parameter, should be placed inside a parenthesis. This prevents accidental operator precedence bugs. For example if the caller passes until(i + 1) then you want it to loop while(!(i+1)) and not while(!i + 1).
From Expert C Programming:
Macro use is best confined to naming literal constants,
shorthand for a few well-chosen constructs. Define the macro name all
in capitals so that, in use, it's instantly clear it's not a function
call. Shun any use of the C preprocessor that modifies the underlying
language so that it's no longer C.
Re: "I'm sure reader know what is the algorithm from code above."
No, it would confuse one even more as the keyword until is not part of the C language. It doesn't take much to type a few extra characters.
That being said, you could do:
#define until(condition) while(!(condition))
Compile your program with:
gcc -E -nostdinc main.c
to see what changes the preprocessor made.
But it would still be an abomination, and not something one would condone.
Using until is useful in select cases.
Sometimes an algorithm or software contract uses until in its definition, so it is good to see that match in code.
Yet re-writing language semantics adds confusion and maintenance costs.
Consider a comment when until is needed.
int i = 0;
// until (i == 2) {
while (i != 2) {
printf("yes\n");
i++;
}
Yes, you can use define for that. See the following example for the macro definition
#include <stdio.h>
#define until(x) while(!(x))
int main() {
int i = 0;
until (i == 2){
printf("iteration %d\n", i);
i++;
}
return 0;
}
If you run it, the output would be
iteration 0
iteration 1
I don't know why you would do this, until is a mostly abandoned keyword for a reason. But this should work:
#define until(cond) while (!(cond))

Modify the indentation of VsCode in C

Good morning, sir,
I use VisualStudio Code to code in C language. I recently discovered the Prettier extension for C, ( and "C/C++")
I saw that I could add an automatic indentation, when I added a ";" or when I saved with Ctrl+S.
with the addition of the lines ;
"editor.formatOnSave": true,
"editor.formatOnType": true
in visual studio's settings.json file.
Now, despite the almost perfect indentation, I wanted to make some adjustments such as the fact that after an initialization of variable type int
there's not a space but a tabulation, like this;
int x;
//rather than;
int x;
as well as for the type of functions
void ft_function(int x);
//rather than ;
void ft_function(int x);
(Because I have a standard to meet, and when I save or what, all the indentation of these variable initializations no longer meets my standard)
I don't know anything about json, and I've just discovered the function so I was wondering if the geniuses in the forum know anything about it, and if so how? At least some leads ^^
I found the setting "C_Cpp.clang_format_style": "{ BasedOnStyle: LLVM, AlignConsecutiveDeclarations: true }"
It works for my variables alignement but not for the functions. Therefore, my functions got auto-indent like this:
int ft_strlen(char *str) {
int i;
i = 0;
while (str[i])
i++;
return (i);
}
I would like something like:
int ft_strlen(char *str) {
int i;
i = 0;
while (str[i])
i++;
return (i);
}
The style you wish to implement, in use in some famous French programming schools such as Epita, Epitech and 42, is not widely implemented in programming environments. The original description, in French, is here.
Using tabs instead of spaces has fallen out of fashion because tab settings vary from one environment to another which breaks code and comment alignment, but for some reason, they are mandated by this document.
Aligning identifiers as they document is just an arbitrary constraint to teach programming students to pay great attention to detail and learn to follow local rules. At 42 for example, they run students' programs through a style checker and fail programs that break the strict presentation rules.
Among other surprising rules in effect there, programmers are taught to use while instead of for, which is highly questionable.
Similarly, I cannot think of a good reason to parenthesize the return value in the return statements.
Configuring Visual Studio Code to reformat your code for these rules does not seem easy without some extra code: if you find a utility to reformat the code to meet these rules, you might be able to register it as a custom filter. Search for moulinette on github... But if you cannot find one, write it yourself, it is a good exercise and will be so useful to your fellow students. You could even patch VSC.

Null statement execution time in C

How does the compiler interpret null statements in C? In terms of execution time. ( empty ";" i.e., without any expression)
And will it optimize code during execution if it encounters null statements, by removing them.
Compilers only care about observable behaviour. Whether you compile
int main() {
;;;;;;;;;;;;;;;;;;
return 0;
}
or
int main() {
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
return 0;
}
does not make any difference regarding the resulting executable. The observable behaviour of both examples is the same.
If you want to convince yourself, look at the compilers output (this is a great tool: https://godbolt.org/z/bnbxiP) or try to profile the above examples (but dont expect to get meaningful numbers ;).
My suggestion is to not think about code as a way to talk to your cpu. When you write code you are not expressing instructions for your cpu. Code is rather a recipe for the compiler and your compiler knows much better how to intruct the cpu than any human. Small difference but I think it helps.

What is the purpose of an 'if (0)' block in if-else block?

My question is about the line I have mentioned in the subject and which I can see in many places inside the production code.
The overall code looks like this:
if (0) {
// Empty braces
} else if (some_fn_call()) {
// actual code
} else if (some_other_fn_call()) {
// another actual code
...
} else {
// default case
}
The other branches are irrelevant to my question. I'm wondering what the meaning of putting if (0) here is. The braces are empty, so I don't think that it is supposed to comment some block of code. Does it force the compiler to make some optimization or are its intentions different?
I have tried to search for this explicit case here on SO and on the internet, but with no success. There're similar questions about JavaScript, but not C. There's another question, What happens when a zero is assigned in an `if` condition?, but it discusses zero assignment to a variable, not the 'if (0)' usage itself.
This can be useful if there are #if statements, ala
if (0)
{
// Empty block
}
#if TEST1_ENABLED
else if (test1())
{
action1();
}
#endif
#if TEST2_ENABLED
else if (test2())
{
action2();
}
#endif
etc.
In this case, any (and all) of the tests can be #if'ed out, and the code will compile correctly. Almost all compilers will remove the if (0) {} part.
A simple autogenerator could generate code like this, as it is slightly easier to code - it doesn't have to consider the first enabled block separately.
I sometimes use this for symmetry so I can move the other else if{ freely around with my editor without having to mind the first if.
Semantically the
if (0) {
// Empty braces
} else
part doesn't do anything and you can count on optimizers to delete it.
I've seen a similar pattern used in generated code. For example, in SQL, I've seen libraries emit the following where clause.
where 1 = 1
This presumably makes it easier to just add on other criteria, because all additional criteria can be prepended with and instead of an additional check to see if it is the first criteria or not.
As written, the if (0) {} clause compiles out to nothing.
I suspect the function of the clause at the top of this ladder is to provide an easy place to temporarily disable all the other functionality at once (for debugging or comparison purposes) by changing the 0 to a 1 or true.
One possibility not yet mentioned: the if (0) { line could be providing a convenient spot for a breakpoint.
Debugging is often done on non-optimised code so the always-false test will be present and able to have breakpoint set on it. When compiled for production, the line of code would be optimised out. The seemingly useless line gives functionality for development and testing builds without impacting release builds.
There are other good suggestions above as well; the only way to really know what the purpose is, is to track down the author and ask. Your source code control system might help with that. (Look for blame-type functionality.)
I am not sure of any optimizations, but my two cents:
This happened because of some code modification, where one primary condition was removed, (the function call in initial if block, let's say), but the developers/ maintainers
were lazy to restructure the if-else block
did not want to go down on the branch coverage count
so instead of removing the associated if block, they simply changed the condition to if(0) and moved on.
It's code rot.
At some point that "if" did something useful, the situation changed, maybe the variable being evaluated was removed.
The person who was fixing/changing the system did as little as possible to affect the logic of the system so he just made sure the code would recompile. So he leaves an "if(0)" because that's quick and easy and he's not totally sure that's what he wants to do. He gets the system working and he doesn't go back to fix it completely.
Then the next developer comes along and thinks that was done deliberately and only comments out that part of the code (since it's not being evaluated anyway), then the next time the code is touched those comments are removed.
I've seen non reachable code blocks in pre-expanded JavaScript that have been generated using a templating language.
For instance, the code you are reading could have been pasted from a server that pre-evaluated the first condition that at that time relied on a variable only available on server side.
if ( ${requestIsNotHttps} ){ ... }else if( ...
which once pre-compiled hences :
if ( 0 ){ ... }else if ( ...
hope this helps you relativise the potential low keyboard activity of the pro-recycling coders era for which i manifest enthusiasm !
That construct may also be used in C to implement generic programming with type safety, relying on the fact that the unreachable code is still checked by the compiler:
// this is a generic unsafe function, that will call fun(arg) at a later time
void defer(void *fun, void *arg);
// this is a macro that makes it safer, by checking the argument
// matches the function signature
#define DEFER(f, arg) \
if(0) f(arg); \ // never actually called, but compile-time checked
else defer(f, (void *)arg); // do the unsafe call after safety check
void myfunction(int *p);
DEFER(myfunction, 42); // compile error
int *b;
DEFER(myfunction, b); // compiles OK
I think it's just bad code. Writing a quick example in Compiler Explorer, we see that in both gcc and clang no code is generated for the if (0) block, even with optimizations completely disabled:
https://godbolt.org/z/PETIks
Playing around with removing the if (0) causes no changes to the generated code, so I conclude that this is not an optimization.
It's possible that there used to be something in the top if block which was later removed. In short, it looks like removing it would cause the exact same code to be generated, so feel free to do that.
As it's been said, the zero is evaluated to false, and the branch will likely be optimized out by the compiler.
I've also seen this before in code where a new feature was added and a kill-switch was needed (if something goes wrong with the feature you can just turn it off), and some time later when the kill-switch was removed the programmer didn't also remove the branch, e.g.
if (feature_a_active()) {
use_feature_a();
} else if (some_fn()) {
...
became
if (0) {
// empty
} else if (some_fn()) {
...
#PSkocik's answer is fine, but I add my two cents. Unsure if I should do this as a comment, or as an answer; choosing the latter, because IMHO worth others seeing, whereas comments are frequently invisible.
Not only do I occasionally use
if(0) {
//deliberately left empty
} else if( cond1 ) {
//deliberately left empty
} else if( cond2 ) {
//deliberately left empty
...
} else {
// no conditions matched
}
But I also occasionally do
if( 1
&& cond1
&& cond2
...
&& condN
) {
or
if( 0
|| cond1
|| cond2
...
|| condN
) {
for complicated conditions. For the same reasons - easier to edit, #ifdef, etc.
For that matter, in Perl I will do
#array = (
elem1,
elem2,
...
elem1,
) {
note the comma at the end of the list. I forget if commas are separators or delimiters in C and C++ lists. IMHO this is one thing we have learned: [Are trailing commas in Perl a bad practice? commas] are a good thing. Like any new notation, it takes a while to get used to.
I compare the if(0) code to lisp
(cond (test1 action1)
(test2 action2)
...
(testn actionn))
which, you guessed it, I may indent as
(cond
(test1 action1)
(test2 action2)
...
(testn actionn)
)
I have sometimes tried to imagine what a more human readable syntax for this might look like.
Perhaps
IF
:: cond1 THEN code1
:: cond2 THEN code2
...
:: condN THEN codeN
FI
inspired by Dikstra's [https://en.wikipedia.org/wiki/Guarded_Command_Language#Selection:_if][Guarded Command Language].
But this syntax implies that the conditions are evaluated in parallel, whereas if...else-if implies sequential and prioritized evaluation of conditions.
I started doing this sort of thing when writing programs that generated other programs, where it is especially convenient.
While we are at it, when writing RTL using Intel's old iHDL, I have coded stuff like
IF 0 THEN /*nothing*/
**FORC i FROM 1 TO 10 DOC**
ELSE IF signal%i% THEN
// stuff to do if signal%i% is active
**ENDC**
ELSE
// nothing matched
ENDIF
where the FORC..DOC..ENDC is a macro preprocessor loop construct, that expands to
IF 0 THEN /*nothing*/
ELSE IF signal1 THEN
// stuff to do if signal1 is active
ELSE IF signal2 THEN
// stuff to do if signal2 is active
...
ELSE IF signal100 THEN
// stuff to do if signal100 is active
ELSE
// nothing matched
ENDIF
This was single assignment, non-imperative, code, so setting a state variable was not allowed, if you needed to do things like find first set bit.
IF 0 THEN /*nothing*/
ELSE IF signal1 THEN
found := 1
ELSE IF signal2 THEN
found := 2
...
ELSE IF signal100 THEN
found := 100
ELSE
// nothing matched
ENDIF
Come to think of it, this may have been the first place that I encountered such constructs.
BTW, the objections that some had to the if(0) style - that the else-if-conditions are sequentially dependent and cannot be arbitrarily reordered - do not apply to AND and OR and XOR logic in RTL - but do apply to short-circuit && and ||.
It helps to debug this block just putting if block 1. This disable all if else block functionality. And also we can expand the if else block.
Actually according to my opinion, if we put any variable for checking inside
e.g:-
public static void main(string args[])
{
var status;
var empList=_unitofWork.EmpRepository.Get(con=>con.isRetired==true);
//some code logic
if(empList.count>0)
{
status=true;
}
if(status)
{
//do something
}
else
{
//do something else
}
}
if then its dynamically get the value in run time and invoke the logic inside it, else its simply extra line of code i guess.
Anybody have any depth knowledge why this thing is used....or agree with me.
kindly respond.
I have seen this used to handle errors, for example
if(0){
lable1:
//do something
}
if(0){
lable2:
//do something
}
.
.
and so on.
if(condition_fails)
goto lable1;
This can be helpful when goto is used to manage errors, statements are executed only when an error occurs. I saw this in very old C-code(where function arguments are written outside the '()' ), don't think anyone follows this now.
I have seen this a few times, I think the most likely reason is it was evaluating something in an older/different version/branch of the code, or possibly for debugging, and changing it to if(0) is a somewhat lazy way of removing whatever was there.

C Language Increment(I Think)

I'll start by saying it's a homework thing, but its got nothing to do with me learning C.
We are tasked to implement solutions to the Reader/Writer conflict using Semaphores and priority. Doing so in Java for the class.
The book we are working with, however uses C(I think) to handle their code examples. I'm not all that familiar with standard C and I can't figure out how to search existing literature for the answer I seek.
In the code:
semaphore x=1,wsem=1;
int readcount;
void reader()
{
While (true){
semWait(x);
readCount++;
if(readcount==1)
{
semWait(wsem);
}
semSignal(x);
READUNIT();
semWait(x);
readcount; /* <--- the questionable command */
if(readcount==0)
{
semSignal(wsem)
}
semSignal(x);
}
}
The line I have "starred" doesn't make any apparent sense. I appears to be simply stating or declaring the name of the variable. Is this some form of decrement I've never seen, or does this do something else? It seems like I'd be able to find it in some C-guide somewhere, but I haven't a clue what it's doing so I don't really know how to ASK what it's doing.
A variable name followed by a semicolon is a complete legal statement in C, but it does nothing. The form is rarely used, although it can be useful to suppress unused-variable warnings in some compilers.
From context, what it was probably supposed to be is readcount--;. That's the C decrement operator, undoing the readcount++ above.
Does your source also have the (erroneous) capital-W While and inconsistent spellings of readcount? If so, that's several bad typos in one short example and you should be suspicious of everything else in the book.

Resources