Recent

Author Topic: C operators and shift  (Read 3883 times)

dseligo

  • Hero Member
  • *****
  • Posts: 1443
Re: C operators and shift
« Reply #15 on: December 06, 2024, 11:06:58 am »
C style operators reduce complexity and thereby cognetive load.

I have to disagree with this. When skimming through, I've read x *= a+b; as x := a+b; While the other x := x*(a+b); was clear as day what it is, and it is why I had to go back and reread the first statement that I had misread. I think that the problem is the way Pascal uses := instead of = for assignments. Hence <whatever symbol>= just looks like a := when skimming through code.

I personally don't like reading cryptic code like x /= -x-- + ++y / -y++;

Exactly.

And his other example:
Code: Pascal  [Select][+][-]
  1. x := x*(a+b)+c;

This is clear in Pascal.
But if it is like this: x *= (a+b)+c; I would have to think if it is x := x * (a+b) + c; or x := x * ((a+b) + c);.

It would be best if C operators in Pascal are deprecated to discourage further use.

Thaddy

  • Hero Member
  • *****
  • Posts: 16300
  • Censorship about opinions does not belong here.
Re: C operators and shift
« Reply #16 on: December 06, 2024, 11:16:20 am »
Totally agree.
If I smell bad code it usually is bad code and that includes my own code.

Warfley

  • Hero Member
  • *****
  • Posts: 1827
Re: C operators and shift
« Reply #17 on: December 06, 2024, 11:30:23 am »
Code: Pascal  [Select][+][-]
  1. x := x*(a+b)+c;

This is clear in Pascal.
But if it is like this: x *= (a+b)+c; I would have to think if it is x := x * (a+b) + c; or x := x * ((a+b) + c);.

It would be best if C operators in Pascal are deprecated to discourage further use.
No offense, but I cannot understand how you would get to that assumption. As soon as you read *= you know it can only ever be a multiplication. You know for certain that no matter what follows, no matter how it's bracketed, etc. it can never do anything other but multiplying. It is strictly information theoretically speaking, less information to parse for your brain while conveying the same meaning.
This is not a matter of taste, I can mathematically prove to you that this expression is less complex

Especially when skimming the code, take for example:
Code: Pascal  [Select][+][-]
  1. MyVector *= <some expression>;
  2. MyVector += <some expression;
You already know that this is first a scaling with some expression and then a translation with some expression. In many cases when skimming through code you first want to get a general feel of what the code does, so you only care "Ok this algorithm does first scaling then translation", without caring for the details of by what it exactly is actually scaled or translated.

You do not have this with normal operations because you always need to do a detailed analysis of the expression. This is especially true because it forces you to split up operations, so instead of:
Code: Pascal  [Select][+][-]
  1. MyVector := MyVector*<ScalingExpr> + <Translation Expr>;
Which is quite a complex expression, with the possibility of lots of errors. While the above split up into *= and += you clearly see whats going on on a first glance.

There is one drawback though, in C and C++ the operation assignment combination is optimized to be inplace. Take the following example:
Code: C  [Select][+][-]
  1. struct MyVec {
  2.     double x, y;
  3.     MyVec &operator+=(MyVec const &rhs) {
  4.         x+=rhs.x;
  5.         y+=rhs.y;
  6.         return *this;
  7.     }
  8. };
The += will update the left hand side of the expression directly. In comparison in Pascal x += y is just a macro for x := x + y, so it always creates a temporary object for the result of the expression. That said for integer types x := x + y is optimized to Inc(x,y);
But for complex types (records, arrays, interfaces, etc.) it does not give a performance advantage as it does in C++

Thaddy

  • Hero Member
  • *****
  • Posts: 16300
  • Censorship about opinions does not belong here.
Re: C operators and shift
« Reply #18 on: December 06, 2024, 11:47:27 am »
Those claims make me slightly uncomfortable, because you can not compare a specific compiler implementation like FPC Pascal(s)  to a generalized C compiler, if ever such a beast existed since K&R.
It is more opinion than fact.
« Last Edit: December 06, 2024, 11:50:02 am by Thaddy »
If I smell bad code it usually is bad code and that includes my own code.

MarkMLl

  • Hero Member
  • *****
  • Posts: 8080
Re: C operators and shift
« Reply #19 on: December 06, 2024, 12:07:28 pm »
I have to disagree with this. When skimming through, I've read x *= a+b; as x := a+b; While the other x := x*(a+b); was clear as day what it is, and it is why I had to go back and reread the first statement that I had misread. I think that the problem is the way Pascal uses := instead of = for assignments. Hence <whatever symbol>= just looks like a := when skimming through code.

Two points here, although like much else in this thread they're "personal opinion" (and to Hell with what the wider programming community expects).

The first is that the FPC documentation explicitly says "Allowed C constructs in Free Pascal ... are just for typing convenience, they don’t generate different code." (Assignments section of the Reference Manual, currently https://www.freepascal.org/docs-html/current/ref/refsu52.html#x161-18500013.1.1). Since that is the official documentation, it takes precedence over any wittering that they're "bad practice" or "have undesirable side-effects" and so on.

The second is that in my opinion the single-character = should be banned from programming languages, because of the extent to which it can be confused for an assignment ( := ) or a comparison ( == ).

Quote
I personally don't like reading cryptic code like x /= -x-- + ++y / -y++;

The autoincrement/decrement operators are very widely considered to be bad news, particularly in a language that bans pointer operations in the name of safety.

MarkMLl
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Logitech, TopSpeed & FTL Modula-2 on bare metal (Z80, '286 protected mode).
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

marcov

  • Administrator
  • Hero Member
  • *
  • Posts: 11980
  • FPC developer.
Re: C operators and shift
« Reply #20 on: December 06, 2024, 01:16:13 pm »
The second is that in my opinion the single-character = should be banned from programming languages, because of the extent to which it can be confused for an assignment ( := ) or a comparison ( == ).

== is a fiction to fix a side effect of the "everything is an expression" mantra of C. Something that many languages don't subscribe to anymore.

It can't be in Pascal as not everything is an expression. and mathematically, = is used for equals, and another operator (usually something like an arrow or =>) for assignment.



MarkMLl

  • Hero Member
  • *****
  • Posts: 8080
Re: C operators and shift
« Reply #21 on: December 06, 2024, 01:57:19 pm »
== is a fiction to fix a side effect of the "everything is an expression" mantra of C. Something that many languages don't subscribe to anymore.

It can't be in Pascal as not everything is an expression. and mathematically, = is used for equals, and another operator (usually something like an arrow or =>) for assignment.

But you can't blame C for that since it was an ALGOLism. So while Wirth fixed it in Pascal, C didn't make the situation any worse than its predecessors.

MarkMLl
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Logitech, TopSpeed & FTL Modula-2 on bare metal (Z80, '286 protected mode).
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

dseligo

  • Hero Member
  • *****
  • Posts: 1443
Re: C operators and shift
« Reply #22 on: December 06, 2024, 01:58:46 pm »
Code: Pascal  [Select][+][-]
  1. x := x*(a+b)+c;

This is clear in Pascal.
But if it is like this: x *= (a+b)+c; I would have to think if it is x := x * (a+b) + c; or x := x * ((a+b) + c);.

It would be best if C operators in Pascal are deprecated to discourage further use.
No offense, but I cannot understand how you would get to that assumption. As soon as you read *= you know it can only ever be a multiplication. You know for certain that no matter what follows, no matter how it's bracketed, etc. it can never do anything other but multiplying. It is strictly information theoretically speaking, less information to parse for your brain while conveying the same meaning.

I know it's multiplication, but I have to think if '+c' is included or not (maybe I have to put whole expression after *= in brackets). When I programmed microcontrollers in C I used brackets extensively, because I was never sure what C will do. It happily compiled what ever I wrote.
Luckily, now I can program AVR controllers in FP.

Quote
This is not a matter of taste, I can mathematically prove to you that this expression is less complex

To compiler is the same, to me is more complex because I have to learn new operators (*=, +=, --, ...) and think how they work.

Quote
Especially when skimming the code, take for example:
Code: Pascal  [Select][+][-]
  1. MyVector *= <some expression>;
  2. MyVector += <some expression;
You already know that this is first a scaling with some expression and then a translation with some expression. In many cases when skimming through code you first want to get a general feel of what the code does, so you only care "Ok this algorithm does first scaling then translation", without caring for the details of by what it exactly is actually scaled or translated.

You do not have this with normal operations because you always need to do a detailed analysis of the expression. This is especially true because it forces you to split up operations, so instead of:
Code: Pascal  [Select][+][-]
  1. MyVector := MyVector*<ScalingExpr> + <Translation Expr>;
Which is quite a complex expression, with the possibility of lots of errors. While the above split up into *= and += you clearly see whats going on on a first glance.

That is also matter of opinion.
To me first example means that you have to take multiple rows into account, and second example is all in one row, so it's easier to see. I see you work with C/C++ by your last example, so it probably seems natural to you, but for me it's strange.

Very clear:
Code: C  [Select][+][-]
  1.     MyVec &operator+=(MyVec const &rhs) {
Ew  :o

alpine

  • Hero Member
  • *****
  • Posts: 1315
Re: C operators and shift
« Reply #23 on: December 06, 2024, 02:51:36 pm »
In my POV, considering the beginnings of the C language more as macro assembly that a real language, most of the specific operators can be recognized as shortcuts for a PDP-11 addressing modes. That includes pre-decrements, post-increments, shortcut-assignments (Dest op Src -> Dest). I'm not experienced with PDP-11 but have with m68k and the similarities are striking. Anyone who has seen a disassembled C program for m68k will confirm how well suited the language is for the architecture.

IMO Claims that shortcut-assignments improve readability are simply ridiculous.
"I'm sorry Dave, I'm afraid I can't do that."
—HAL 9000

Seenkao

  • Hero Member
  • *****
  • Posts: 648
    • New ZenGL.
Re: C operators and shift
« Reply #24 on: December 06, 2024, 04:01:40 pm »
Я не считаю что нужны лишние сокращения. Зачем сокращать код ради пары символов, только ради того чтоб это можно было делать? Что вам мешает потратить на 1-2 секунды больше и сделать код более понятным остальным?

Есть две проблемы в программировании:
1 - когда стараются всё минимизировать.
2 - когда стараются всё слишком подробно расписать.

По второму более развёрнуто. Вы не уместите в название функции всё что она делает. Не сможете отобразить всю её функциональность. Но очень часто смотришь на чужой код и видишь там длинную функцию состоящую из 10 слов...

И вот тут у меня возникает вопрос: а зачем вам эта минимизация, если у вас функцию надо набирать так долго, что минимизации кода за ней не видно?

----------------------------
Google translate:
I don't think that unnecessary abbreviations are necessary. Why shorten the code for the sake of a couple of symbols, just so that it can be done? What's stopping you from spending 1-2 seconds more and making the code more understandable to others?

There are two problems in programming:
1 - when they try to minimize everything.
2 - when they try to describe everything in too much detail.

The second one is more detailed. You won't be able to fit everything that the function does into the name. You won't be able to display all its functionality. But very often you look at someone else's code and see a long function consisting of 10 words...

And here I have a question: why do you need this minimization, if your function takes so long to type that you can't see the code minimization behind it?
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Thaddy

  • Hero Member
  • *****
  • Posts: 16300
  • Censorship about opinions does not belong here.
Re: C operators and shift
« Reply #25 on: December 06, 2024, 05:44:43 pm »

== is a fiction to fix a side effect of the "everything is an expression" mantra of C. Something that many languages don't subscribe to anymore.
I am confused, I thought == is a platform in ASCII crt games? In that sense it can be used in Pascal.  %) :-[
dtbt.
« Last Edit: December 06, 2024, 05:46:26 pm by Thaddy »
If I smell bad code it usually is bad code and that includes my own code.

Warfley

  • Hero Member
  • *****
  • Posts: 1827
Re: C operators and shift
« Reply #26 on: December 06, 2024, 05:58:44 pm »
I don't think that unnecessary abbreviations are necessary. Why shorten the code for the sake of a couple of symbols, just so that it can be done? What's stopping you from spending 1-2 seconds more and making the code more understandable to others?

There are two problems in programming:
1 - when they try to minimize everything.
2 - when they try to describe everything in too much detail.

The second one is more detailed. You won't be able to fit everything that the function does into the name. You won't be able to display all its functionality. But very often you look at someone else's code and see a long function consisting of 10 words...

And here I have a question: why do you need this minimization, if your function takes so long to type that you can't see the code minimization behind it?
It's not about shortening, infact I argue that even
Code: Pascal  [Select][+][-]
  1. Inc(x,<Expr>);
Is better than
Code: Pascal  [Select][+][-]
  1. x:=x+<Expr>;
Even though it is longer.

What I argue is not minimization but specialization. The C style operators like the Inc and Dec intrinsics are more specialized. When you write
Code: Pascal  [Select][+][-]
  1. x := <EXPR>
Expr can be anything, it could be a constant, it could add something to x, it could subtract something from x, multiply, shift or divide x. You need to always read the full expression to figure out what is going on.
For example:
Code: Pascal  [Select][+][-]
  1. x := a*x + b*x;
Is the same as
Code: Pascal  [Select][+][-]
  1. x *= a+b
But the former takes much more mental load to parse. When you encounter +=, -=, *=, /= or Inc and Dec, you already know what is happening to x before having to parse the whole expression.
When I see:
Code: Pascal  [Select][+][-]
  1. Inc(x,<Expr>);
I know from the beginning of the statement, x will be incremented by something. If I on the other hand have (worst case):
Code: Pascal  [Select][+][-]
  1. x := <Expr> + x;
I only see that it is an increment at the very end of the statement. So I need to read much more to get the same information.

Using more specialized functionality allows the programmer to think more clearly about the problem at hand. It's the exact same reason why there is a while, repeat-until and for loop in Pascal, even though you can trivially replace each of those by each other. Infact you can easily replace any loop by goto.
Why don't we all use goto? Because having more specialized syntactic constructs makes code easier to read, write and maintain

Seenkao

  • Hero Member
  • *****
  • Posts: 648
    • New ZenGL.
Re: C operators and shift
« Reply #27 on: December 06, 2024, 06:17:30 pm »
Warfley, вы можете говорить только за себя. Когда вы учите математику, вам изначально показывают формулы, где указаны все переменные. Человек, пришедший со знаниями математики, будет так же основываться на те знания что он получил. Ему будут не известны ни "Inc", ни "dec", ни тем более "+=", "-=", "*=" или "/=".
Если человек будет читать и видеть переменную в формуле, то он и будет воспринимать её, как содержащуюся в формуле и ни как иначе интерпретировать её не будет. Все ваши сокращения ведут именно к большему непониманию происходящего большей части программистов.

Привыкнуть можно? Да, можно.
Нужно? Нет, не нужно!

Не надо усложнять людям жизнь. Паскаль и так не очень популярен, но прибегая к вашим решениям, вы сделаете его более C-подобным, но не более популярным.

И заметьте, я не против того чтоб вы этим пользовались или кто-то ещё! Но не надо это продвигать! Посмотрите на C++, где одну спецификацию надо будет изучать несколько лет.

Не заморачивайтесь этой ерундой, делайте код. Не усложняйте ЯП Паскаль!

--------------------
Google translate:
Warfley, you can only speak for yourself. When you study mathematics, you are initially shown formulas where all the variables are indicated. A person who came with knowledge of mathematics will also rely on the knowledge he received. He will not know "Inc", nor "dec", and especially "+=", "-=", "*=" or "/=".
If a person reads and sees a variable in a formula, then he will perceive it as contained in the formula and will not interpret it in any other way. All your abbreviations lead precisely to greater misunderstanding of what is happening for the majority of programmers.

Is it possible to get used to it? Yes, it is possible.
Is it necessary? No, it is not necessary!

No need to complicate people's lives. Pascal is not very popular anyway, but by using your solutions you will make it more C-like, but not more popular.

And mind you, I am not against you or anyone else using it! But don't promote it! Look at C++, where you will have to study one specification for several years.

Don't bother with this nonsense, make code. Don't complicate the Pascal PL!
Rus: Стремлюсь к созданию минимальных и достаточно быстрых приложений.

Eng: I strive to create applications that are minimal and reasonably fast.
Working on ZenGL

Warfley

  • Hero Member
  • *****
  • Posts: 1827
Re: C operators and shift
« Reply #28 on: December 06, 2024, 09:37:29 pm »
Warfley, you can only speak for yourself. When you study mathematics, you are initially shown formulas where all the variables are indicated. A person who came with knowledge of mathematics will also rely on the knowledge he received. He will not know "Inc", nor "dec", and especially "+=", "-=", "*=" or "/=".
If a person reads and sees a variable in a formula, then he will perceive it as contained in the formula and will not interpret it in any other way. All your abbreviations lead precisely to greater misunderstanding of what is happening for the majority of programmers.

Pascal is not based on mathematical formalism, the only languages that are of mathematical nature are those based on lambda calculus.
Yes inc, and dec are not part of mathematics, so is begin, end, if, while, etc. If you only restrict yourself to mathematics you cannot write a single syntactically correct Pascal program.

Pascal is a high level language, if you are not willing to learn high level concepts you shouldn't be using it.

Quote
Is it possible to get used to it? Yes, it is possible.
Is it necessary? No, it is not necessary!
You can say the exact same thing about literally any Pascal language feature. Infact if that is your approach to programming languages, why do you use anything other than assembly? Literally any Pascal feature is not necessary because you can just use raw assembly.

MarkMLl

  • Hero Member
  • *****
  • Posts: 8080
Re: C operators and shift
« Reply #29 on: December 06, 2024, 10:39:08 pm »
You can say the exact same thing about literally any Pascal language feature. Infact if that is your approach to programming languages, why do you use anything other than assembly? Literally any Pascal feature is not necessary because you can just use raw assembly.

The bottom line is that Pascal is a programming notation, and that for the last 30 years or so there have been certain notations or idioms which are so widely accepted that to refuse to omit them invites ridicule: += is one of those notations.

If somebody wants to start arguing "mathematical purity" then I'll raise them by giving examples from APL: which I am sure they'll know was designed by a mathematician. Does anybody seriously believe that introducing a transcendental function to eliminate a conditional operation is really a good idea?

MarkMLl

p.s. I trust OP (the originator of this thread) appreciates the demon he has unleashed >:-)
MT+86 & Turbo Pascal v1 on CCP/M-86, multitasking with LAN & graphics in 128Kb.
Logitech, TopSpeed & FTL Modula-2 on bare metal (Z80, '286 protected mode).
Pet hate: people who boast about the size and sophistication of their computer.
GitHub repositories: https://github.com/MarkMLl?tab=repositories

 

TinyPortal © 2005-2018