Author Topic: Converting assembly to C  (Read 24300 times)

0 Members and 26 Guests are viewing this topic.

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 8349
  • Country: fi
    • My home page and email address
Re: Converting assembly to C
« Reply #100 on: April 04, 2025, 08:41:22 pm »
One other thing. Just because I currently had a statement that shall not be named in my code, doesn't mean that I could have eventually come to understand C well enough to possibly, maybe, perhaps, eventually remove said highly offensive statement from the code???
From what I can tell, you started well along constructing the intermediate form for the code, as I outlined in the latter section of my reply #72.  Up to #14, I think the process started flowing, with the only real risk being you being satisfied with an un-maintainable intermediate version of the code.  I particularly liked radiolistener's switch..case in #13.

It started to go awry in #15.  Macros, just like gotos, have their uses.  As an example, I often use the construct
    // explanation of what CONFIG_VARIABLE controls
    #ifndef  CONFIG_VARIABLE
    #define  CONFIG_VARIABLE  default-value
    #endif
for my unit tests because it allows me to trivially rebuild the code with a different value, using -DCONFIG_VARIABLE=value compiler option (for GCC and Clang).

Especially in the intermediate representation of the code, it is very useful to replace magic numeric constants with macros.

In #22, you should have included the code itself between [CODE]..[/CODE] tags, because attachments like that are opened separately, so require extra effort to review the code.  Inline code is better than any attachment, if you want many eyes on it.

In #25, tggzzz tried to get the thread back to rails by telling you (metertech58761) to concentrate on understanding and describing what the code does, instead of translating the code; something I repeated much later in #72.

In #29, metertech58761 tried to push back on the language authoritarianism, but to no avail.  😟  I tried to defuse the silly arguments from authority in #53 by describing counter-cases that are easy for anyone to verify for themselves.  In #56, I was still amused by the silliness of (illogicality and authority-driven) repeated arguments, but by #58, I determined that radiolistener wasn't interested in logical rational discussion, only defending their self-view and opinions.  I tried to describe the reasons why those claims were silly in #68 and #70, also trying to point out how many people misunderstand MISRA-C and DO178B to be coding standards, which they definitely are not: they are about the entire process, with the coding stuff just a subset chosen to make the process more efficient.  The coding stuff alone, without the review-testing-verification cycles, will not bring any significant reliability/safety improvements, and therefore cannot be used as a guide to what kind of code is "safer" or "good" per se.

It is unfortunate that metertech58761's project thread got mired in language-authoritarianism (using Names and Status as proofs that certain practices are infallible and have no exceptions).  It is very common in software threads, though.

The way I deal with this, is temporarily ignore the members I believe I cannot mutually beneficially interact with, using Profile > Summary, then Modify Profile > Buddies/Ignore List... > Edit Ignore List.  I periodically empty that list, because I don't use it to "silence" others, I only use it to control what I react to.  (For example, I do believe that if radiolistener had slightly more humility and much less authority-based/axiomatic assertions, they'd be a great asset for this forum and especially learners.  I don't want them to be silent or to go away, I just want them to change how they argue.  I also wish Picuino would realize that popularity and quality do not correlate in real life, but I don't seem to be able to sway their belief on that.)

I hope that metertech58761 and others reading this thread realize that even when their threads get mired like this, it does not mean the thread is lost: it just means they need to filter the content to focus on the technical aspects they grasp, and continue.  (Asking the other discussers to stop will not work, and is often seen as an attempt of controlling what others discuss and thus hostile.  I recommend against doing that.)
« Last Edit: April 04, 2025, 08:43:44 pm by Nominal Animal »
 
The following users thanked this post: Picuino

Offline Picuino

  • Super Contributor
  • ***
  • Posts: 1460
  • Country: es
    • Picuino
Re: Converting assembly to C
« Reply #101 on: April 04, 2025, 09:17:22 pm »
We are human and we are not even talking. We must not forget that with writing we lose many of the nuances of face-to-face speech and this tends to create a multitude of misunderstandings.
Nor should we forget that we are human. Full of illogical thoughts about popularity or authority, full of ideas based on logical fallacies and full of prejudices and biased ideas.
That a logical conversation can emerge from this breeding ground (and sometimes it does) is a true miracle.
 

Offline radiolistener

  • Super Contributor
  • ***
  • Posts: 5733
  • Country: Earth
Re: Converting assembly to C
« Reply #102 on: April 04, 2025, 09:49:24 pm »
Countering that by an argument from authority –– essentially, "I'm an expert, trust me bro", or "You think you know better than X?" –– is idiotic.  It is what most humans do in social situations, yes, but in a technical discussion it is ridiculous and shows that the person is not interested in discussing the reasoning and logic behind their current understanding and opinions, and is instead engaging in social games like "saving face" and "looking for admiration" and "one-upmanship".

The only way to stop that that seems to work, is to insult the person who engages in that, in the hopes that they will reflect on it (some time in the future, perhaps weeks or months later), and adjust their output and interaction with other technical people.  Ignoring such behaviour will only mislead others into believing there might be merit in that.  All that is required for nontechnical bullshit to prevail is for rational logical people to ignore it.

It’s important to clarify something. I haven't relied on "arguments from authority." Instead, I’ve provided specific, practical examples of how using goto - even in seemingly harmless ways - can lead to serious maintenance, readability, and tooling issues in real-world projects. These are technical concerns grounded in experience, not appeals to status.

Ironically, by ignoring and dismissing these examples without addressing their substance and instead assuming your own position is unquestionably correct, you're doing exactly what you criticize: relying on your own perceived authority. By your logic, that would justify me responding with insults rather than reasoned arguments. And yet, I’ve chosen not to follow that path.

I believe that in a technical exchange, it’s far more productive and respectful - to engage with logic and real-world implications rather than try to assert dominance through hostility.

If the goal is to improve understanding and code quality, let’s focus on that, not on undermining each other personally.

(I'm sure that if I had better social skills, I could point that behaviour out in some sarcastic manner that is effective but is not personally insulting.)


Your problem isn’t a lack of social skills - it’s that the particular social skill you’ve developed happens to be confrontation. You're clearly experienced in using insults and provocation as tools in discussion. Instead of engaging in a technical dialogue about the use of goto, you focus on asserting your opinion as the only correct one (as the sole valid perspective) and as a result, you resort to insulting those who disagree, attempting to silence them and prevent others from hearing any viewpoint that challenges your own. That’s likely why it unsettles you when others disagree - it threatens the narrative you’re trying to impose as authoritative. You’re not aiming to exchange views, but to control how the issue is perceived.

Lacking the technical background to directly counter the points raised, you resort to personal attacks. This is a well-known manipulation tactic: diverting attention from substance to conflict when there’s no solid ground left to stand on. Unfortunately, this highlights where your real proficiency lies - not in engineering principles, but in derailing conversations through hostility. Perhaps that’s why you instinctively shift the discussion from reasoned argument to emotional escalation: because you recognize that in technical discourse, your position is weak, whereas in personal attacks and verbal aggression, you feel confident and experienced. It’s a deliberate move into a domain where you believe your strengths will give you the upper hand.

After all, by your own admission, insults appear to be your most reliable fallback when a technical argument doesn’t go your way. Isn't it?


With your strong inclination to dominate the conversation, dismiss dissenting voices, enforce a single narrative, and resort to aggression when challenged, you might have thrived in an environment built on authoritarian control and a dictatorship regime. However, in technical fields, such qualities tend to hinder collaboration and innovation rather than support them. Leadership in engineering demands openness to critique, respect for differing viewpoints, and the ability to engage constructively - even in the face of disagreement.


Unfortunately, this is common in technical fields when a young specialist, having gained a solid understanding of a particular topic, starts to view themselves as an authority. When someone expresses an opinion that challenges their views, it can deeply affect them, leading them to respond with aggression, insults, and other negative behaviors toward those who dared to disagree. They may believe that such a confrontational stance will help them maintain the position of being "always right," but in practice, life will eventually teach them that this tactic doesn't work in the long run.
« Last Edit: April 04, 2025, 10:29:03 pm by radiolistener »
 

Offline radiolistener

  • Super Contributor
  • ***
  • Posts: 5733
  • Country: Earth
Re: Converting assembly to C
« Reply #103 on: April 04, 2025, 11:41:26 pm »
Especially in the intermediate representation of the code, it is very useful to replace magic numeric constants with macros.

Using macros for magic numbers can lead to significant issues. Instead, it's better to use constants, enums, or inline functions, which provide better type safety, easier debugging, and improved maintainability. These alternatives make your code more robust and easier to manage in the long run.

Some reasons for that:
- Macros do not provide type safety. Since the preprocessor simply replaces the macro with its value before compilation, there's no way to check if the types are compatible at compile time. This can lead to unintended behavior and hard-to-find bugs.
- Macros don't provide the benefits of debugging and inspecting variables at runtime, unlike constants or enums. When debugging, you can't see the macro's value as a variable in the debugger. It's just a "text replacement" that could be anywhere in your code, making it difficult to track down problems related to its usage.
- Macros are globally visible and don't have the scoping rules that functions, constants, or enums do. This means that you might accidentally redefine or clash with existing macros in other parts of the code, leading to hard-to-diagnose issues.
- Macros don’t provide debugging or symbol information like constants or enums. If you replace a macro with an enum or a constant, debuggers and tools can give you more meaningful information when inspecting your program’s state.
- Macros don’t provide any semantic meaning beyond their value. When you use constants, enums, or inline functions, your code becomes more readable and maintainable because it’s clear what each value represents, and they can be easily refactored or modified if necessary.
 

Offline Picuino

  • Super Contributor
  • ***
  • Posts: 1460
  • Country: es
    • Picuino
Re: Converting assembly to C
« Reply #104 on: April 06, 2025, 07:39:54 pm »
There is even the right to be wrong, without that justifying in any way personal attacks.
Absolutely not.  Logical fallacies like arguments from authority are anti-science, anti-engineering, and need to be burned with fire and scorn in technical discussions.  They are no better than using religion as a basis for technical and scientific decisions, and must be scorned, or we will fail.

Rules for primarily social interaction differ from those for technical discussions.

In a technical discussion, we do not pose opposing opinions.  That is what social people do.  It does not work for technology or science, because reality is not a social construct.  Instead, we discuss the reasons behind those opinions.  The opinions themselves are worthless; in fact, they have negative worth, unless the reasons behind those opinions are discussed, because only those reasons and experience can be compared.  Opinions themselves are simply the current conclusion, and if stated in the "this is my opinion, take it what you will" manner, simply clutter a technical discussion without bringing anything that could be rationally and logically examined into it.

To simplify, opinions in isolation are worth shit, and deserve no respect.  They are simply the conclusion, the wrapping paper around the thing itself.

I and others have described why specific uses of goto are warranted, in an effort to prove that a blanket statement like "using goto makes your code inferior and shitty" is simply provably incorrect; that it should be reserved for the very few cases where its use is better than any alternatives, but those few cases do exist.  To generalise, no rule of thumb covers the entire domain, only a small subset of it.

Countering that by an argument from authority –– essentially, "I'm an expert, trust me bro", or "You think you know better than X?" –– is idiotic.  It is what most humans do in social situations, yes, but in a technical discussion it is ridiculous and shows that the person is not interested in discussing the reasoning and logic behind their current understanding and opinions, and is instead engaging in social games like "saving face" and "looking for admiration" and "one-upmanship".

The only way to stop that that seems to work, is to insult the person who engages in that, in the hopes that they will reflect on it (some time in the future, perhaps weeks or months later), and adjust their output and interaction with other technical people.  Ignoring such behaviour will only mislead others into believing there might be merit in that.  All that is required for nontechnical bullshit to prevail is for rational logical people to ignore it.

(I'm sure that if I had better social skills, I could point that behaviour out in some sarcastic manner that is effective but is not personally insulting.)

Me saying "radiolistener is full of shit" is a colloquial expression intended exactly in that sense.  I am not at all interested in online social dances and games; I am interested in problem solving, discussing understanding and experience (leading to various opinions), and helping others learn.

If you find this attitude or approach distasteful/unwanted/negative, take it up with Dave and the moderators.  (I mean this at its face value: it is something you should try to discuss with them, if you have any kind of logical reasons for believing so.  If you simply believe so or take that as an axiomatic truth, or expect technical people to respect even illogical and provably untrue opinions, do be ready to be laughed at.)

Please, do not try to passive-aggressively hint or indicate that it is somehow inferior/unwanted/negative in the hopes of changing others' behaviour: that is social, and this is a technical forum.  Not everyone has the social sensibilities you do: what you think and believe is natural and professional conduct, is pure social nonsense to others, and vice versa.  The only thing we can really rely on, as shown by the past few centuries, is rational and logical thought, the scientific method, and engineering.  As social animals, humans are easily misled using interaction tricks like logical fallacies and appealing to social hierarchies and popularity; those never lead to good technical or scientific outcomes.  I know you believe in the wisdom of the herd and that popularity correlates with technical quality, but in science and engineering, those beliefs have been proven incorrect time and time again.


I agree that logical fallacies and, in general, illogical and pseudo-religious arguments should not be part of a technical or scientific discussion. However, the reality is that they are used, and frequently.
From this fact what one would have to know is how to respond to that way of expressing oneself and this is where I differ from your way of expressing yourself in the previous message. And I am a bit surprised by your message because you do not usually behave in the way you defend.
The response to an illogical argument should, according to you, be aggressive to the point of insult, but it is not the right way to act in any internet forum, although it is also a fact that such behaviors exist.

It has seemed appropriate to me to take this discussion to another thread where it does not hinder the current thread and we can focus on dealing with this particular issue:

https://www.eevblog.com/forum/chat/aggressive-responses-considered-harmful/
 
The following users thanked this post: DiTBho

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 8349
  • Country: fi
    • My home page and email address
Re: Converting assembly to C
« Reply #105 on: April 06, 2025, 10:09:05 pm »
I agree that logical fallacies and, in general, illogical and pseudo-religious arguments should not be part of a technical or scientific discussion. However, the reality is that they are used, and frequently.
From this fact what one would have to know is how to respond to that way of expressing oneself and this is where I differ from your way of expressing yourself in the previous message. And I am a bit surprised by your message because you do not usually behave in the way you defend.
When logical fallacies or axiomatic beliefs are used instead of rational arguments, I do not recommend an immediately aggressive approach, true.
It is when they insist on it, and include social games as I mentioned, when I take out the matches and gasoline.

The reason for the aggressiveness in that case is twofold: one is the rejection of rational-logical discourse, which is an absolute requirement in a technical discussion.  Any rejection of it will lead to failure.  The other is social manipulation tactics, which I personally detest to the extreme.  You see, I am personally very easy target for social manipulation, and am easily exploited because of that.  I am becoming old enough to detect the signs, and have found that many people use social tactics to manipulate others without even noticing it themselves –– it is a skill they've developed unknowingly, and apply it because it works.  I truly hate exploitation.  In combination, this means that when such social tactics are applied, even if unwittingly/instinctively, my reaction will always be aggressive.

I have seen the damage such social tactics cause to technical projects, discussion, and understanding.  I can list a number of technically very inferior and insecure software projects that are only funded and maintained because of social tactics.  These projects are all well known for their horrible security history, filled with CVEs involving privilege escalation bugs going unnoticed and possibly exploited in the wild for years.

I reject any suggestion that avoids confrontation when that occurs.

The response to an illogical argument should, according to you, be aggressive to the point of insult, but it is not the right way to act in any internet forum, although it is also a fact that such behaviors exist.
And exactly why do you claim it is not the right way to act?

My reasoning is shown above: because showing aggressive opposition to the behavioural pattern above is required to stop it harming the discussion/project/understanding.  Unless you can show a response pattern that is at least as effective, I say your opinion on this is irrelevant, because your suggestion does not work in practice.

(Note that while the optimum result would be to change that persons communications patterns, that rarely happens immediately; it takes repeated pushback for this to have that effect.  What it does do, however, is make it easier for others, especially "lurkers", to see how the discussion is being manipulated by social tactics, and apply their own logic and do their own research wrt. the claims shown, to avoid being misled.)

To repeat: all it takes for social manipulation and illogic to work and lead to technically inferior results, is for technical people to be silent about it.

In this case, it is utterly clear that while radiolisteners first response was excellent and useful, their followup posts, if taken at face value, would lead to technically inferior results and unnecessarily limited process.  (Avoiding the use of goto in the intermediate representation makes the work much, much harder, because instead of changing the representation as a first step, using goto for assembly branches and jumps, one has to directly write the corresponding "non-goto" C construct at once; this easily leads to bugs, because the intermediate representation is no longer visible, and thus cannot be checked.)

[aggressive responses considered harmful -thread]
That is set of axiomatic beliefs that leaves no room for discussion.  It is written in the technical style –– I see you used the old social trick of adapting the style I used in why writing style and grammar matters in posts, but replacing the reasoning portions with axiomatic statements in a technical-looking style that leaves no room for argument or dissent.

Well done.  It is a perfect example of a post that will be appreciated by those who agree with your beliefs, but leaves no room for rational discussions on your axiomatic statements, and therefore is unlikely to garner any opposing responses, thus reinforcing your belief in your axioms.  That post is a perfect example of the social games I often mention, even though I truly believe you did this in good faith.

Consider how anyone having a solid logical reason why your axiomatic "rules" are incorrect would/could respond to you?  The way you wrote your post leaves no room for such discussion.  Even the title is the conclusion expected from such discussions.  (That alone is a social trick, exploiting the agreeableness human personality trait (and specifically its compliance sub-trait), starting by discreetly explaining what is expected of others.)

I'd be willing to bet 2€ that you will only get responses from members that simply agree with you.  If that happened to me, I'd be alarmed and disappointed in my own writing style.  The best case to me is always a discussion, even an argument, or an expansion or delving deeper into the details and exceptions to the initial statement.  If my post leaves no room for that, it is simply a statement and not a discussion; something far less useful.  (I'm particularly unhappy with how I started this and this thread.  If I had posed those as questions –– even if I had one possible answer myself that I wanted to show to others and discuss ––, the discussion would likely have included other, perhaps even better approaches, with mine just as an example.  As it is, they are not very useful threads, and didn't reach details a questioning approach could have; thus wasteful/disappointing.)
« Last Edit: April 06, 2025, 10:17:12 pm by Nominal Animal »
 
The following users thanked this post: Siwastaja, JPortici

Online nctnico

  • Super Contributor
  • ***
  • Posts: 30132
  • Country: nl
    • NCT Developments
Re: Converting assembly to C
« Reply #106 on: April 06, 2025, 11:40:47 pm »
Now, I don't see any reason to use goto at all. And it's important to note - not because it's considered bad practice, not for religious reasons, and not because any particular group of people or company believes it's wrong, but simply because I don't see any practical situations where goto would be beneficial, especially since I know more effective solutions that can be implemented without it.

That's an ultra-common topic as it seems and comes back on a regular basis.
You'll find the usual, "goto's are bad" and "those who say goto's are bad are just ignorant wankers with no practical experience".

I'm not sure either are very useful, but hey. There's little as polarizing as programming topics. And politics.

I often like to start with the obvious, that is the rationale of the original paper it originates from, which was just trying to convince people of the benefits of structured programming, which was absolutely not a given at the time. These days, nobody reaosnable would even question "structured programming", so that context is almost entirely lost.

The second point is that, apart from assembly with "branches", most uses of "goto" are in C and C++ when it's a convenient and efficient way of breaking out of some nested loops, or for error handling, where you have a function with many possible paths of error and a single point to go to to handle the error before returning. That's mostly for lack of better constructs, not at all because goto is cute, even less so an elegant way of dealing with program flow. But it works given the limitations of those languages.

Some other languages have proper ways of dealing with the same, like named loops (which are coming with C23 if I'm not mistaken?) and 'defer' constructs. I don't think anyone sane would prefer using "goto" rather than those two alternatives, but of course, YMMV.

Now even in C, there are ways you can often avoid goto for typical error handling, which I tend to prefer these days, although that's relatively recent. Instead of using goto, I'll wrap code that can produce errors in "do {...} while (false)" constructs, which I just 'break' out of after setting an error value, in case of error. The error value is tested after this "loop", and that often looks cleaner. Additional benefit is you can ultra easily turn this construct into "retry" construct by changing changing the do...while to a for with a certain number of iterations.

For breaking out of nested loops, unfortunately, I have no magic trick (until we get named loops). One common way of avoiding 'goto' in this case is to use flags, but that often looks clunky and is possibly less efficient, depending on the order in which you place the flag test in the loop conditions. Occasionally, it can make things more readable, as it shows the complete condition of a loop in only one place, but most often, it's just clunky.
I agree.

In C you can consider the use of 'continue' as a goto as well. IMHO what should drive the use of goto / continue is whether it leads to code which is easier to understand (*). Code which is easier to understand is less prone to bugs (including ones added later on through code modifications) and cheaper to maintain. Sometimes structuring code to make it simple requires a bit more work to write. Just like writing a short, to the point letter takes more time than three pages of rambling which doesn't get the message across.

* So far my practical use of goto in C is limited to jumping to do a single cleanup in case an init has failed. The Linux kernel is riddled with this programing pattern. Including situations where it is less appropriate with several exit points which makes code less easy to follow / maintain (as Radiolistener already noted).
« Last Edit: April 07, 2025, 12:08:36 am by nctnico »
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline Siwastaja

  • Super Contributor
  • ***
  • Posts: 11154
  • Country: fi
Re: Converting assembly to C
« Reply #107 on: April 07, 2025, 06:28:19 am »
I'd be willing to bet 2€ that you will only get responses from members that simply agree with you.

So true that I had to intervene and add some disagreement  :box:
 
The following users thanked this post: JPortici, Nominal Animal, 5U4GB

Offline Picuino

  • Super Contributor
  • ***
  • Posts: 1460
  • Country: es
    • Picuino
Re: Converting assembly to C
« Reply #108 on: April 07, 2025, 12:05:48 pm »
[aggressive responses considered harmful -thread]
That is set of axiomatic beliefs that leaves no room for discussion.  It is written in the technical style –– I see you used the old social trick of adapting the style I used in why writing style and grammar matters in posts, but replacing the reasoning portions with axiomatic statements in a technical-looking style that leaves no room for argument or dissent.

Well done.  It is a perfect example of a post that will be appreciated by those who agree with your beliefs, but leaves no room for rational discussions on your axiomatic statements, and therefore is unlikely to garner any opposing responses, thus reinforcing your belief in your axioms.  That post is a perfect example of the social games I often mention, even though I truly believe you did this in good faith.

Consider how anyone having a solid logical reason why your axiomatic "rules" are incorrect would/could respond to you?  The way you wrote your post leaves no room for such discussion.  Even the title is the conclusion expected from such discussions.  (That alone is a social trick, exploiting the agreeableness human personality trait (and specifically its compliance sub-trait), starting by discreetly explaining what is expected of others.)

I'd be willing to bet 2€ that you will only get responses from members that simply agree with you.  If that happened to me, I'd be alarmed and disappointed in my own writing style.  The best case to me is always a discussion, even an argument, or an expansion or delving deeper into the details and exceptions to the initial statement.  If my post leaves no room for that, it is simply a statement and not a discussion; something far less useful.  (I'm particularly unhappy with how I started this and this thread.  If I had posed those as questions –– even if I had one possible answer myself that I wanted to show to others and discuss ––, the discussion would likely have included other, perhaps even better approaches, with mine just as an example.  As it is, they are not very useful threads, and didn't reach details a questioning approach could have; thus wasteful/disappointing.)

Fortunately the initial post is generating debate. It is true that I started it with a series of affirmations that I believe are not open to discussion, but it was not my intention to make a closed discourse and I was relatively convinced that there would be contrary opinions. I only hope that the debate does not degenerate into useless discussion.
 

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 8349
  • Country: fi
    • My home page and email address
Re: Converting assembly to C
« Reply #109 on: April 07, 2025, 11:44:18 pm »
I'd be willing to bet 2€ that you will only get responses from members that simply agree with you.
Fortunately the initial post is generating debate.
:-//

I never, ever claim I'm always right.  (That's also why my current opinions are not worth anything, just like everyone elses, only the reasoning, logic, and experiences that lead to those opinions matters.)  And when I'm wrong, I do clearly admit it; just look at my posting history.

While I don't think the thread responses have much to do with your first post, and are more generally about why certain behavioural patterns occur in online discussions (and what exactly constitutes trolling), I do agree I would have lost that bet.  If there is an IBAN account or purpose you want me to put that 2€ towards, just say so or PM me the details.
 
The following users thanked this post: thm_w

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 8349
  • Country: fi
    • My home page and email address
Re: Converting assembly to C
« Reply #110 on: April 08, 2025, 12:08:36 am »
Here's the rewrite after some structural work to get the three two-way suites into one.

I can't see how to minimize the goto statements - most are attached to conditionals, the only 'hard' goto statements are returning to the main loop or to the error handler.

Code: [Select]

// Two-way unit test suite (LMT-2 / MCT-2xx / DCT-501)

// Variables guiding this suite:
// testSet: 0 (test), 1 (install), 2 (read + test), 3 (DCT read), or 8 (short read)
// uutType: 2 = LMT-2 / MCT, 4 = DCT

suite2:

if (testSet == 1) { test15(); } // download address to UUT

suite2_01:

test20(); // Read / verify UUT address

if (testSet == 0)
{
test20a(); // display UUT address

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_01; }
}

if (testSet == 3) { goto suite2_12; } // DCT tests

// Test 25: Get hardware ID

suite2_02:

dispBlank(); // Clear 4x20 LCD
testNum(25); // LCD top row: '25: Get Hardware ID '

msgBtemplate(); // Default template for 2-way messages
msgDataQry(); // Request data from UUT

if (testSet == 8)
{ if (uutType != 2) { goto suite2_04; } }

// Error-check data based on UUT response
// Error 5: Other Data error

if ((msgRec[1] & 0x1F) != (addrM & 0x1F)) { goto error5; }
if (msgRec[2] != addrL) { goto error5; }

// Address check passed, so save UUT data

uutFWbyte = msgRec[3]; // Firmware number
uutFWspec = msgRec[4]; // Firmware revision
optbyte = msgRec[5]; // Installed option (i.e., latching relay)

// Determine UUT group based on firmware
// We have units with S00036 and S00095 on hand

suite2_03:

// S00001 - suspected LMT-1
// S00036 - LMT-2
if (uutFWbyte == 1 || uutFWbyte == 36) { uutGroup = 2; goto suite2_05; }

// S00074 - MCT-212, MCT-213, MCT-22x
// S00093 - MCT-240, MCT-242
if (uutFWbyte == 74 || uutFWbyte == 93) { uutGroup = 4; goto suite2_05; }

// S00088 - MCT-210
// S00095 - MCT-210, MCT-213
if (uutFWbyte == 88 || uutFWbyte == 95) { uutGroup = 6; goto suite2_05; }

// S00008 - suspected DCT
// S00033 - DCT-501
if (uutFWbyte == 8 || uutFWbyte == 33) { goto suite2_21; }

// We have now gone through all the known FW specs - so we have a problem

// Error 7: Unknown firmware

suite2_04:

readout = 7; // LCD row 1 RH: 'Error 7', row 2: 'Unknown Firmware!'
getFWRev(); // read again, display data on row 3

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_02; }

uutGroup = 4;

if (testSet == 8) { goto suite2_06; }
else { goto suite2_08; }

// Now let's get the DCT check from the tree out of the way

suite2_21:

if (uutType == 4) { goto suite2_08; }
else { goto suite2_04; }

// If we did not request the short read script, skip ahead!

suite2_05:

if (testSet != 8) { goto suite2_07; }

// Begin short read (tests 45, 47, 48)

suite2_06:

test_45(); // Get and display reading (kilowatthours)

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_03; }

// Unless we are testing LMT-2s, we are finished - return to main menu

if (uutGroup != 2) { goto loopMain; }

test_47(); // Get and display reading (pulse initiator 2)

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_03; }

test_48(); // Get and display reading (pulse initiator 3)

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_03; }

// Finished with short read - return to main menu

goto loopMain;

// Now we continue from the intermission

suite2_07:

if (uutType != 2) { goto suite2_04; }

// Validate the presence of latched relay and FCT Control Number
// optByte bit 0 leads the way
// Error6: Incorrect FCT Control #

if (optByte && 1 == 0)
{ if (fctCtlNum != 0) { goto error6; } } // bit 0 = 0, so fctCtlNum MUST be 0
else
{ if (fctCtlNum == 0) { goto error6; } } // bit 0 = 1, so fctCtlNum CANNOT be 0

suite2_08:

ledStat = 7; // LCD display (row TBD): 'ID successful'
displayRefresh();
wait(1000); // Wait 1000mS = 1 second

// Now we find our way outta here into the actual test suite

if (testSet != 1) { goto suite2_09; }

if (uutType == 4) { goto suite2_11; }

if (uutGroup == 2) { goto suite2_11; }
else { goto suite2_10; }

// Main suite

suite2_09:

test_26(); // Get UUT test mode status

if (lmtTestMd != 0) { if (uutType == 4) { goto suite2_14; } }

test_27(); // Enable test mode in UUT

suite2_10:

test_28(); //  MCT related - perhaps for entry of multiplier, Mp, or Kh?

if (uutGroup == 6) { test_29(); } // MCT related - may be for multiplier, Mp, or Kh?

suite2_11:

test_30(); // Reset error flags, inhibit time sync, reset battery time

suite2_12:

if (uutGroup == 0) { goto suite2_13; } // possible skip for when CCU is being read

if (uutGroup != 2) { goto suite2_18; }

suite2_13:

test32(); // function TBD

// exit if DCT group was selected

if (testSet == 3)
{
ledStat = 7; // LCD display (row TBD): 'Test group complete '
displayRefresh();
keyMask = 0b01001000;
goto loopMain;
}

suite2_14:

if (uutType == 2) { goto suite2_18; }

// DCT test group


suite2_15:

test_61(); // Read Analog 1 - 2nd row, left

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_15; }

test_62(); // Read Analog 2 - 2nd row, right

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_15; }

test_63(); // Read Analog 3 - 3rd row, left

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_15; }

test_64(); // Read Analog 4 - 3rd row, right

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_15; }

// optByte bit 1 seems to be flag for relay type in DCT - timed or latched

if (optByte && 2 == 0)
{

suite2_16:

test_70(); // Download bytes $3A - $3D and TOU delay status flags from DCT

test_71(); // sends long-form message to UUT

test_72(); // Strobe DCT relays

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_16; }

test_73(); // Write dctData1 - dctData4 back to $3A - $3D in DCT

}

else
{

test_75(); // fetch flag from DCT, save in dctData1

suite2_17:

test_76(); // Relay tests

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_17; }

}

if (testSet != 1) { test_78(); } // turn off test mode in DCT

test_80(); display toggle switch status

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_15; }

// LCD display (row TBD): 'Test group complete '
keyMask = 0b01001000;
goto loopMain;

suite2_18:

test_35b(); // Exercise timed relays

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_18; }

suite2_19:

test_40b(); // Exercise latched relay

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_19; }

suite2_20:

test_46(); // Display Pulse initiator count

// Display 'Repeat / Next?' on LCD row 4
while((ch = getKey()) != KEY_NEXT)
{ if (ch == KEY_REPEAT) goto suite2_20; }

if (testSet != 1) { test_50(); } // Turn off test mode in UUT

// LCD display (row TBD): 'Test group complete '
keyMask = 0b01001000;
goto loopMain;

// End of 2-way tests
I took the liberty of expanding the code inline, as it makes it much easier to read the code.

Have you progressed any further on this yet?

The pattern of

    label:
        do stuff
        while((ch = getKey()) != KEY_NEXT)
            { if (ch == KEY_REPEAT) goto label; }

are easiest to implement as a separate function, and telling the C compiler that these functions cannot be called from external code and the compiler is free to inline them.  One possibility is, for example,

    static void do_label(void) {
        int  ch;
       
        while (1) {
            do stuff;
           
            while (1) {
                ch = getKey();
                if (ch == KEY_NEXT)
                    return;
                if (ch == KEY_REPEAT)
                    break;
            }
        }
    }

although others exist.  (Your main code would simply call do_label() for each test suite.  Do think of better, more descriptive names, though.)

I'm having a bit of difficulty concentrating on this, so I'm hoping other members (radiolistener and Picuino included) will suggest even better (easier to read and maintain) patterns; my point is that there is a clear path forwards, and something like this would be my next step.  (I admit, I personally would need to put this particular code aside for a couple of days due to the related discussions affecting me negatively, before I'd be able to get the results I'd be happy with.)

I suspect that for me, the end result would be a state machine, so an alternative approach would be to construct the state diagram from the code as it is now, and reimplement that.  This one has enough parts that instead of drawing it by hand in Dia or Inkscape or other tools, I'd use Graphviz for this, defining the structure in DOT language.  If you want an example of that, install Graphviz for your system (it's free and available for all OSes), and I can show how I'd describe at least the first few suites in DOT, and what the ensuing state graph I'd do would look like.
« Last Edit: April 08, 2025, 12:15:30 am by Nominal Animal »
 

Offline Picuino

  • Super Contributor
  • ***
  • Posts: 1460
  • Country: es
    • Picuino
Re: Converting assembly to C
« Reply #111 on: April 08, 2025, 02:17:05 pm »
I'd be willing to bet 2€ that you will only get responses from members that simply agree with you.
Fortunately the initial post is generating debate.
:-//

I never, ever claim I'm always right.  (That's also why my current opinions are not worth anything, just like everyone elses, only the reasoning, logic, and experiences that lead to those opinions matters.)  And when I'm wrong, I do clearly admit it; just look at my posting history.

While I don't think the thread responses have much to do with your first post, and are more generally about why certain behavioural patterns occur in online discussions (and what exactly constitutes trolling), I do agree I would have lost that bet.  If there is an IBAN account or purpose you want me to put that 2€ towards, just say so or PM me the details.

Since you acknowledge being indebted to me, I would like to collect it from you in a simpler way.
I usually greatly appreciate your responses and the temperance with which you express them.
Considering that in this matter I consider you not to have a strong bias, I will be paid if you contribute with your opinion to the thread I opened, when you consider it appropriate (today or in a year).
 

Offline Perkele

  • Regular Contributor
  • *
  • Posts: 71
  • Country: ie
Re: Converting assembly to C
« Reply #112 on: April 08, 2025, 08:13:33 pm »
Especially in the intermediate representation of the code, it is very useful to replace magic numeric constants with macros.

- Macros don't provide the benefits of debugging and inspecting variables at runtime, unlike constants or enums. When debugging, you can't see the macro's value as a variable in the debugger. It's just a "text replacement" that could be anywhere in your code, making it difficult to track down problems related to its usage.

Eclipse CDT was able to resolve macros on-the-fly while debugging. At least it was able to do this five years ago.

BTW. how does one resolve compile-time computations without macros in case when pre-C23 compilers are used?

And what about functions which on some platforms execute an action, and on other platforms they are effectively a no-op and should not get executed?
Because it is likely that one might not want to push/pop registers because of a no-op.

Quote
- Macros are globally visible and don't have the scoping rules that functions, constants, or enums do. This means that you might accidentally redefine or clash with existing macros in other parts of the code, leading to hard-to-diagnose issues
Can you please clarify this one and define what does "globally visible" mean?
 

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 8349
  • Country: fi
    • My home page and email address
Re: Converting assembly to C
« Reply #113 on: April 08, 2025, 10:55:08 pm »
Since you acknowledge being indebted to me
Don't be ridiculous.  I acknowledged I would have lost that bet, out of honesty.  That's all.

Never, ever mistake humility for weakness or honesty for capitulation.  Some of us have a strict mental backbone, and value humility and honesty as mutually beneficial human interaction strategies –– when reciprocated.  When they are exploited, we retaliate.

In particular, I wrote reply #110 to OP and others who are uninterested in the religious dogma/programming axioms posed by some and the tone policing attempts, and would rather just discuss useful technical stuff instead.

I usually greatly appreciate your responses and the temperance with which you express them.
I strive for mutually beneficial discussions based on logic and rational thought.  When axiomatic beliefs and logical fallacies are substituted for logic, I escalate.  When social gaming/tricks –– even if inadvertent ––, I escalate.  The three last steps in that ladder are sarcasm/humor/poking fun, aggression, and personal insults.  This is not a personal "preference"; it is simply what I've found works best.  Do recall that I do not have the innate social skills most people have; I've had to empirically learn those the same way others learn math, science, or engineering.  Lots of observation and analysis.

(I'm not emotionless, though.  Sometimes my emotions get the better of me, like they do for most other people.  None of that here, though: all I've felt is frustration with seemingly reasonable but functionally incorrect advice.  It is very much what I feel when the output of LLMs is taken as intelligence, or the TIOBE popularity index is considered as an useful gauge of programming languages due to "wisdom of the herd".)

I would suggest that instead of telling others to stop using such tools, you try to find at least equally functional tools of discourse, and then start a thread showing others how and why those tools work and are superior.

(Think about it: wasn't my grammar thread exactly that? Now, compare to your own initial intent for your own thread.)

Do note that in online discussions such as these, the discussers are surrounded by a huge crowd just listening in.  My goal here is to help everyone not be misled by incorrect/dysfunctional advice –– by others, or even by myself –– and to notice the most useful advice.  You can see this in my posting history, if you care to check.  I will not let any feelings or social niceties get in the way of that in technical discussions, because good advice is more important than appearance or feelings.

As it is, your new thread sounds to me like "When you respond to my unfounded beliefs stated as truths with aggression and insults, I feel bad inside.  Please stop!  Just because I'm wrong does not give you the right to point it out to others.  I have the right to mislead others, if I want to!" – just clad in technical-seeming form.  It's already spread from the definition of "trolling" into specific details in childhood psychology by people with no knowledge of psychology.  Utterly useless bickering, I believe.
 
The following users thanked this post: tooki

Online SiliconWizard

  • Super Contributor
  • ***
  • Posts: 17774
  • Country: fr
Re: Converting assembly to C
« Reply #114 on: April 09, 2025, 03:17:26 am »
Especially in the intermediate representation of the code, it is very useful to replace magic numeric constants with macros.

Using macros for magic numbers can lead to significant issues. Instead, it's better to use constants, enums, or inline functions, which provide better type safety, easier debugging, and improved maintainability. These alternatives make your code more robust and easier to manage in the long run.

Some reasons for that:
- Macros do not provide type safety. Since the preprocessor simply replaces the macro with its value before compilation, there's no way to check if the types are compatible at compile time. This can lead to unintended behavior and hard-to-find bugs.
- Macros don't provide the benefits of debugging and inspecting variables at runtime, unlike constants or enums. When debugging, you can't see the macro's value as a variable in the debugger. It's just a "text replacement" that could be anywhere in your code, making it difficult to track down problems related to its usage.
- Macros are globally visible and don't have the scoping rules that functions, constants, or enums do. This means that you might accidentally redefine or clash with existing macros in other parts of the code, leading to hard-to-diagnose issues.
- Macros don’t provide debugging or symbol information like constants or enums. If you replace a macro with an enum or a constant, debuggers and tools can give you more meaningful information when inspecting your program’s state.
- Macros don’t provide any semantic meaning beyond their value. When you use constants, enums, or inline functions, your code becomes more readable and maintainable because it’s clear what each value represents, and they can be easily refactored or modified if necessary.

While there can be many pitfalls with those macros from the C preprocessor (used both by C and C++), I am personally against cutting off their use altogether (as you seem to suggest), because there's no serious alternative for many things, at least in particular with C. When using C++, there are a lot more tools available to avoid them (but C++ brings its own set of issues... which is another topic entirely/)

Of course, again, as I mentioned for 'goto', if you work in an environment where "macros" are forbidden, the story ends there. Exposing the fact they are forbidden and the underlying rationale is interesting, but "debating" it is pointless, when you have no choice.

With that said, I'll comment some of your points above:
- Type safety: true, but in C, enums do not provide any type safety either past being an 'int'. They even end up in the global namespace. The only real benefit is to group some definitions logically in enums for the developer and reader's benefit, but that's pretty much it. At least you can't use a string literal as an enum value, at least if your compiler is not too dumb or permissive. Yeah, not that pretty either. The situation is a bit better in C++ for sure, although simple enums are still compatible with int's in a number of contexts, making them barely any better than in C, except for the namespacing. You need to use "enum class" in C++ to get something with more strict typing.
- Using functions rather than macros when appropriate is generally a good idea. Qualifying them "inline" allows you to define such functions in header files and reuse them everywhere while avoiding multiple definitions. You can alternatively qualify them just "static", but the "inline" qualifier conveys the intent better IMO. Just a detail. Any decent optimizing compiler will just emit code that's inlined and usually as efficient as a macro.
- Decent debuggers know about macros - at least for defining "constants" (ie. named literals). GDB certainly does. Of course, function-like macros are harder to deal with when debugging though, but that's expected.
- Macros provide semantic as long as you pick decent names for them, following some general code style and sticking to it, instead of cryptic ones.
- As "ugly" as they may look, past the cases above, macros allow things that are otherwise impossible to do without - when you want some genericity. Again, in C, which was the center of this thread. In C++, you have templates, with their own possible downsides, but still much more elegant for writing generic code.
- Bonus pitfall: in C, "const" is definitely not a "constant" in the sense you meant - it's a read-only variable. There are a few ways in which it is quite different from a macro just substituting a literal. For instance, you normally can't use a const variable as a size for a global array. As for local arrays, you can, but you'll make them VLAs doing so, whether you like it or not. Yes yes, even if it's a "const".

All this, along with goto, and I know I'm just repeating myself, but this is very specific to C and languages with similar limitations. With C++, you have constexpr and templates. With Ada, you have more features at your disposal to make all of the above completely moot than you could even think of.

Just a few points.
« Last Edit: April 09, 2025, 03:23:38 am by SiliconWizard »
 

Offline Siwastaja

  • Super Contributor
  • ***
  • Posts: 11154
  • Country: fi
Re: Converting assembly to C
« Reply #115 on: April 09, 2025, 07:19:19 am »
Code: [Select]
#include <stdio.h>

int i = 3;

int main()
{
int i = 4;
printf("%d\n", i);
return 0;
}

$ gcc t.c -Wall -Werror && ./a.out
4

Code: [Select]
#include <stdio.h>

#define i 3

int main()
{
#define i 4
printf("%d\n", i);
return 0;
}

$ gcc t.c -Wall -Werror && ./a.out
t.c: In function ‘main’:
t.c:7: error: "i" redefined [-Werror]
    7 |  #define i 4
      |
t.c:3: note: this is the location of the previous definition
    3 | #define i 3
      |
cc1: all warnings being treated as errors


Conclusion: macros are safer than variables. Variables considered harmful.
 

Offline DiTBho

  • Super Contributor
  • ***
  • Posts: 5090
  • Country: gb
Re: Converting assembly to C
« Reply #116 on: April 09, 2025, 11:26:42 am »
Decent debuggers know about macros - at least for defining "constants" (ie. named literals). GDB certainly does.

Yup, I can confirm this about GDB.
The opposite of courage is not cowardice, it is conformity. Even a dead fish can go with the flow
 

Offline radiolistener

  • Super Contributor
  • ***
  • Posts: 5733
  • Country: Earth
Re: Converting assembly to C
« Reply #117 on: April 09, 2025, 01:24:55 pm »
Of course, again, as I mentioned for 'goto', if you work in an environment where "macros" are forbidden, the story ends there. Exposing the fact they are forbidden and the underlying rationale is interesting, but "debating" it is pointless, when you have no choice.

Usually, macros are not entirely forbidden in most environments, but it's important to use them with caution and avoid overusing them. While they can be powerful, they also come with risks like lack of type safety and harder debugging. Unlike goto, which is generally banned outright in most coding standards, macros are typically allowed but expected to be used responsibly and sparingly.

 

Offline metertech58761Topic starter

  • Frequent Contributor
  • **
  • Posts: 271
  • Country: us
Re: Converting assembly to C
« Reply #118 on: April 09, 2025, 02:36:27 pm »
cool story, people. Came here looking for guidance, and I got a holy war in return. Not sure where I go from here.

Edit: toned it down a bit.
« Last Edit: April 09, 2025, 07:54:19 pm by metertech58761 »
 

Offline tggzzz

  • Super Contributor
  • ***
  • Posts: 23122
  • Country: gb
  • Numbers, not adjectives
    • Having fun doing more, with less
Re: Converting assembly to C
« Reply #119 on: April 09, 2025, 04:29:26 pm »
cool story, people. Came here looking for guidance, and I got a holy war in return. Not sure where I go from here.

You read and understand the various points that have been made. Then apply those which seem applicable to your case. Preferably without shouting.

If you were expecting to be handed the answer on a plate, then stackexchange might be a better venue. It is good for problems with a simple solution. (But your problem isn't simple.)
There are lies, damned lies, statistics - and ADC/DAC specs.
Glider pilot's aphorism: "there is no substitute for span". Retort: "There is a substitute: skill+imagination. But you can buy span".
Having fun doing more, with less
 

Offline Siwastaja

  • Super Contributor
  • ***
  • Posts: 11154
  • Country: fi
Re: Converting assembly to C
« Reply #120 on: April 09, 2025, 06:58:56 pm »
Not sure where I go from here.

I can recommend Stack Overflow for you. It's a Q&A site, which EEVBlog forum is not. They have strong moderation and focus on just answering the question, and any tangential content, even if on-topic for the site but not exact answer for the question, is downvoted and automatically hidden, or moderated away.

You can also try LLM's like ChatGPT if they are helpful.
 

Offline metertech58761Topic starter

  • Frequent Contributor
  • **
  • Posts: 271
  • Country: us
Re: Converting assembly to C
« Reply #121 on: April 09, 2025, 07:59:03 pm »
tggzzz: The thread took a turn deep into "this pedantic semantics argument helps me how?" territory. Lost interest once the post count went well beyond 50 with minimal involvement on my part.

Siwatsja: Noted. When and if, especially if, I want to resume this, I'll look into setting up an account over there. Thank you.
 

Offline Siwastaja

  • Super Contributor
  • ***
  • Posts: 11154
  • Country: fi
Re: Converting assembly to C
« Reply #122 on: April 10, 2025, 06:04:08 am »
The thread took a turn deep into "this pedantic semantics argument helps me how?" territory.

This happens to every thread where radiolistener appears, nearly every time. Don't take it too seriously; learning how to skip messages is a valuable skill on discussion forums. Just keep discussing your stuff with those who give useful responses to you. You can thus help keep the discussion on your desired track. If you panic and run away, or start shouting others to shut up, then it's game over.
 

Offline Nominal Animal

  • Super Contributor
  • ***
  • Posts: 8349
  • Country: fi
    • My home page and email address
Re: Converting assembly to C
« Reply #123 on: April 10, 2025, 06:52:56 am »
Lost interest once the post count went well beyond 50 with minimal involvement on my part.
Like Siwastaja wrote, just skip the noise, perhaps even temporarily ignore some members (Profile > Summary, Modify Profile > Buddies/Ignore List ... > Edit Ignore List).  Online, you need to be selective and tenacious to get good results.

To add to what I suggested in #110, you could also consider replacing the interaction pauses with

    ch = interactive_wait("Repeat / Next?", keymask);

where the function does the LCD display and waits until one of the buttons specified in the keymask set is pressed, then returns that value.  (If you only have the two buttons, the mask is not needed.)

You'll see that this simplifies many of the loops where the current form still uses goto; you can also combine this with the sub-function approach I showed in #110.

This is also a perfect example of when simulating the user interface can help a lot.  Seeing as you use C on a very limited microcontroller, I would suggest a very simple command-line/terminal program, using either termios (Linux/Unix/BSD/mac/WSL2) or Curses, with a very simple single-file program skeleton providing the LCD display functions, waiting for the repeat/next keypress (or other keys), and a debug logging so that the individual tests (like test15();) are mocked up by functions that just visibly log something like "Test 15 now running".

That way, you can easily test different refactorings of the test suite sequence and user interface.  Like I mentioned in #110, I suspect that a simple state machine describing the menu structure, each node naming a function to call, text shown on the LCD, and pointers to structures for each key when pressed, would probably yield more easily maintained C code.  (Plus, if you run from Flash, those structures are also in Flash and not in RAM.)
    typedef  struct suite  suite;
    struct suite {
        void (*tests)(void);
        const char *display;
        const struct suite *repeat;
        const struct suite *next;
    };

The nice side of this is that it is easy to then document the navigation hierarchy (at build time) using a simple program that emits Graphviz DOT language graph of the tests, with each node having the display text, and labeled arrows pointing to the nodes advanced to when pressing next or repeat.
 

Online nctnico

  • Super Contributor
  • ***
  • Posts: 30132
  • Country: nl
    • NCT Developments
Re: Converting assembly to C
« Reply #124 on: April 12, 2025, 01:50:26 pm »
:-DD No, that's just your misunderstanding, confusing bad uses of a tool for the tool itself, and therefore labeling the tool bad.  Your viewpoint is utterly simplistic, and therefore ridiculous.

If you knew anything about maintainable code or avoiding bugs, you'd know that the Linux kernel has much lower bug density compared to any enterprise code.  Your own company, even if producing code used for critical life-sustaining equipment, almost certainly has a higher bug density; the only way you're not mired in lawsuits is a strict review and testing cycle (or clients that just don't notice or know any better).  Labeling certain tools as "shitty" and "poor quality" is just their way of trying to wrangle lower-quality developers like yourself into producing something that can be shipped after sufficiently rigorous testing and review.
Having worked on medical device projects that undergo regular testing and audits, I can confidently say that, compared to the level of rigor I have observed in such environments, the Linux kernel is a mess of poorly structured code with numerous bugs. However, this is not to say that Linux is inherently bad or mismanaged - I fully recognize that it is a free, community-driven project that lacks the level of funding necessary to enforce strict development practices. In fact, considering these constraints, I’d say it is holding up remarkably well, and I genuinely appreciate its development. That said, comparing it to large-scale commercial projects with significantly stricter methodologies and regulatory requirements would simply be incorrect.
I agree here. Having 20+ years of experience fixing & modifying the Linux kernel myself I can say the Linux kernel is a prime example of extremely poorly written C code. The code is very frugal and I have seen it break in places leading to hard to trace bugs. Most recently due to changes to the way GPIO pins are enumerated. Not all drivers got updated but due to the lack of using a specific type the compiler doesn't even throw a warning and good lucking using code analysis tools. As a result some drivers get fed with illegal values resulting in all kinds of odd behaviour. This cost me a day I could have spend on doing something useful instead of figuring out somebody has messed up the GPIO handling.
« Last Edit: April 12, 2025, 02:02:54 pm by nctnico »
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 
The following users thanked this post: cfbsoftware, radiolistener, DiTBho


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf