Author Topic: C word  (Read 50528 times)

0 Members and 6 Guests are viewing this topic.

Offline PerranOakTopic starter

  • Frequent Contributor
  • **
  • Posts: 579
  • Country: gb
C word
« on: September 12, 2019, 03:38:09 pm »
I've succumbed to the pressure to learn C to programme microcontrollers instead of using assembly.

It seems to be going well but I get stuck on, I guess, simple things. For example:

while (b!=0)
… and …
while (b==0)

I understood that "==" is a check of "equal to" but it took ages to realise that the "!" meant "not ". I'm sure I came across this earlier but evidently forgot.

So, is there a resource (online?) that I can go to for simple help like this?

Cheers.
You can release yourself but the only way to go is down!
RJD
 

Offline nugglix

  • Regular Contributor
  • *
  • Posts: 209
  • Country: de
Re: C word
« Reply #1 on: September 12, 2019, 03:48:29 pm »
The search term would be something along "operators in c".

This would reveal something like:
https://www.tutorialspoint.com/cprogramming/c_operators.htm

Exchanging operators with keywords in the search could lead to:
https://www.programiz.com/c-programming/c-keywords-identifier

 

Offline Bassman59

  • Super Contributor
  • ***
  • Posts: 2499
  • Country: us
  • Yes, I do this for a living
Re: C word
« Reply #2 on: September 12, 2019, 05:32:59 pm »
So, is there a resource (online?) that I can go to for simple help like this?

Start here.
 

Offline obiwanjacobi

  • Super Contributor
  • ***
  • Posts: 1030
  • Country: nl
  • What's this yippee-yayoh pin you talk about!?
    • Marctronix Blog
Re: C word
« Reply #3 on: September 12, 2019, 05:51:54 pm »
Wrong code should not compile!
 

Offline golden_labels

  • Super Contributor
  • ***
  • Posts: 2439
  • Country: pl
Re: C word
« Reply #4 on: September 12, 2019, 06:56:25 pm »
PerranOak
I support obiwanjecobi’s suggestion — cppreference is the most well prepared reference for C and C++ I have seen in my life. In particular it covers important topics, which are often ommited even from most books (perhaps because authors do not really understand them), like the strict aliasing rule.

If you are just doing this as a hobby, you may skip this post and just enjoy coding.

But beware: programming in C is like walking through a minefield. Programming in C without a copy of the latest standard at hand is like dancing drunk on a minefield under artillery fire. And I am not talking about the infamous manual memory management, buffer overflows and so on. The true trap is that intuitive interpretation of what a given C code does may wildly differ from what it actually does. It can catch anyone with their pants down. It even happens to seasoned programmers. To the point at which Linus Torvalds, the man behind Linux (the kernel), is blaming compilers for properly interpreting his code — properly in terms of what language defined, but not in the way he believed it works.

If you want to go professional — and especially if safety or security will depend on your code — be fully aware that you should dig into that hard to understand mess of specifications spread across 650 pages. If you can’t get a copy of the latest C standard — and I do not suggest paying 180€ for it just to use the language — you may legally download the latest standard draft from the working group. The draft is nearlyt he same as the final version. You may also consider reading Stack Overflow often, in particular things related to Undefined Behaviour.

Don’t be fooled into thinking that C is “close to bare metal”. <justified-exaggeration> The only “bare metal” to which it is close is PDP-11,</justified-exaggeration> which is dead for over 30 years. Don’t assume that given code will have any specific representation in the compiled binary. In particular this may be a PITA on microcontrollers — through the years I’ve came across a few low-level constructs that are not reliably expressible with C. E.g. operations timing: while with proper code the compiler will not reorder operations like setting pins, it may reorder/move other operations, changing relative time at which setting pins occurs.

Finally, a nice and famous example of why C may be hell:
Code: [Select]
unsigned short a = 65535u;
unsigned short b;

b = a * a; // UB on some platforms! :D
The marked line is undefined behaviour on platforms with 16-bit unsigned short and 32-bit int. To make things more puzzling: the UB is caused by signed overflow [sic! “signed”, not “unsigned”]. Compilers will likely convert that to code that does what most people would suspect it to do, but it is accidential.
Why 📎 | We live in times when half of people have IQ below 100.
 
The following users thanked this post: digsys

Offline janoc

  • Super Contributor
  • ***
  • Posts: 3958
  • Country: de
Re: C word
« Reply #5 on: September 12, 2019, 07:36:20 pm »
https://en.cppreference.com/w/ (There is both C and C++ reference, despite the domain name)

https://devdocs.io/ (Select the languages you want - fast reference doc access)

E.g. on the comparison operators:
https://devdocs.io/c/language/operator_comparison
https://en.cppreference.com/w/c/language/expressions
« Last Edit: September 12, 2019, 07:39:24 pm by janoc »
 

Offline rstofer

  • Super Contributor
  • ***
  • Posts: 10088
  • Country: us
Re: C word
« Reply #6 on: September 12, 2019, 09:19:20 pm »
Don’t be fooled into thinking that C is “close to bare metal”. <justified-exaggeration> The only “bare metal” to which it is close is PDP-11,</justified-exaggeration> which is dead for over 30 years.

Maybe just on life support...  I have two of the PiDP11/70s running 2.11BSD Unix.  These are the original disks running on a PDP11/70 emulation by 'simh' on a Raspberry Pi.  I rather enjoy old-school and this emulation has 4 MB of RAM and runs faster than the real machine.

https://obsolescence.wixsite.com/obsolescence/pidp-11

There's a lot of interest in older systems, particularly those you can get your arms around.


 

Online SiliconWizard

  • Super Contributor
  • ***
  • Posts: 17782
  • Country: fr
Re: C word
« Reply #7 on: September 12, 2019, 10:48:01 pm »
Just a suggestion here - maybe actually learn C?
 :-//
 

Offline digsys

  • Supporter
  • ****
  • Posts: 2239
  • Country: au
    • DIGSYS
Re: C word
« Reply #8 on: September 12, 2019, 10:56:42 pm »
They'll move me away from machine code over my dead cold body :-)
Hello <tap> <tap> .. is this thing on?
 

Offline hamster_nz

  • Super Contributor
  • ***
  • Posts: 2860
  • Country: nz
Re: C word
« Reply #9 on: September 12, 2019, 11:04:17 pm »
Find a quick reference card..

Google "ansi c quick reference filetype:pdf"
« Last Edit: September 12, 2019, 11:07:00 pm by hamster_nz »
Gaze not into the abyss, lest you become recognized as an abyss domain expert, and they expect you keep gazing into the damn thing.
 

Offline golden_labels

  • Super Contributor
  • ***
  • Posts: 2439
  • Country: pl
Re: C word
« Reply #10 on: September 13, 2019, 12:31:51 am »
Skimming over that quick reference card, there are few things to note.
  • The main function “template” is syntactically invalid. While in backward compatibility mode some compilers may accept that K&R-ism, it is not a part of C for 20 years.
  • The example for a macro definition is exactly how they shouldn’t be used. It will cause double evaluation of one of its arguments.
  • The description for #include is not making sense. Neither the definition of the language, nor how the compilers work fits “library” and “user” distinction (and what “user file” would be?)
  • static has double meaning and only one of them is listed.
  • “Pointer to int, float… *int, *float” — what?
  • const is not a constant. With exception of enum, C has no constants.
  • It differentiates between two use scenarios of sizeof, suggesting they are different in syntax, while in fact they aren’t.
  • The description of strncpy may suggest it produces a c-string that contains n first characters of the source string. It doesn’t. strncpy isn’t made to work with c-strings, it’s purpose was to handle — now no longer normally used — fixed-length strings. It will either produce a thing that isn’t a proper c-string, or will waste cycles on padding zeros (not to be confused with terminating zero). The function to copy at most n first characters of a string is strncat with the destination string being initially empty.
  • The description of memcpy misses the very important requirement that the areas do not overlap. memcpy is also an archaism that has no use nowadays: memmove does the job safely and there is no reason to use the former one.
  • bsearch misses the requirement that the array must be sorted.
  • The format description for printf and scanf is shared, despite there are minor differences. Notably %f in scanf indicates a float, not a double as it does for printf (which has no way to accept float).
On top of that there are issues that will not be a problem if someone already knows the language and uses the list as a cheatsheet, but if someone wants to learn from it, there are a few more catches:
  • The sizes for integers are the minimum requirements, not the actual values — yet there is no mention of that.
  • unsigned is non-negative, not positive.
  • system is listed and the reference may give an impression of its usefulness, while in fact the function is so ill-defined that its use in real world scenarios is very limited.
  • ctime and asctime are traps, as they depend on a shared state and their results should be immedietely copied to another buffer. While that goes beyond basic C, in multithreaded programs they can’t even be reliably used without providing proper program-wide locking mechanism on both of them and locale, which is unlikely to occur in libraries.
Why 📎 | We live in times when half of people have IQ below 100.
 

Offline rstofer

  • Super Contributor
  • ***
  • Posts: 10088
  • Country: us
Re: C word
« Reply #11 on: September 13, 2019, 02:18:10 am »
“The C Programming Language” ANSI Edition
 
The following users thanked this post: radioactive

Offline radioactive

  • Regular Contributor
  • *
  • Posts: 173
  • Country: us
Re: C word
« Reply #12 on: September 13, 2019, 02:21:24 am »
 

Offline AndyC_772

  • Super Contributor
  • ***
  • Posts: 4560
  • Country: gb
  • Professional design engineer
    • Cawte Engineering | Reliable Electronics
Re: C word
« Reply #13 on: September 13, 2019, 09:57:49 am »
On top of that there are issues that will not be a problem if someone already knows the language and uses the list as a cheatsheet, but if someone wants to learn from it, there are a few more catches:
  • The sizes for integers are the minimum requirements, not the actual values — yet there is no mention of that.

That's quite an interesting 'gotcha' for embedded programmers.

Not so long ago I was caught out writing an SPI driver for an STM32F7.

This particular device has a feature called 'packed writes' (or something along those lines). The way it works is:

- if you perform an 8-bit write to the SPI data register, it clocks out 8 bits.
- if you perform a 16 (or more) bit write to that exact same register, it clocks out 16 bits.

You've probably already guessed the problem - the driver inserted '0' bytes in between each data byte, because the compiled code used a 32-bit write instruction to copy each individual byte into the data register, and the hardware dutifully interpreted this as a 'packed' write, 16 bits wide, with bits 8..15 = 0.

Needless to say, it took a while to find that one, and a while longer to work out where exactly I needed to add (uint8_t) to force an 8-bit write.

Offline PerranOakTopic starter

  • Frequent Contributor
  • **
  • Posts: 579
  • Country: gb
Re: C word
« Reply #14 on: September 13, 2019, 11:35:16 am »
Brilliant, thanks all.

SiliconWizard: yes, that's exactly what I am doing! It was literally "day 1" and I wondered if there was an additional resource available that I could use when my course book needed a helping hand … or I did(!)
You can release yourself but the only way to go is down!
RJD
 

Offline Karel

  • Super Contributor
  • ***
  • Posts: 2540
  • Country: 00
Re: C word
« Reply #15 on: September 13, 2019, 11:36:36 am »
 

Offline PerranOakTopic starter

  • Frequent Contributor
  • **
  • Posts: 579
  • Country: gb
Re: C word
« Reply #16 on: September 13, 2019, 11:41:37 am »
BTW books on C (e.g. The C Programming Language by Kernighan and Richie): do they cover any peculiarities (are there any) when using C in programming microcontrollers?
You can release yourself but the only way to go is down!
RJD
 

Online SiliconWizard

  • Super Contributor
  • ***
  • Posts: 17782
  • Country: fr
Re: C word
« Reply #17 on: September 13, 2019, 02:30:17 pm »
SiliconWizard: yes, that's exactly what I am doing! It was literally "day 1" and I wondered if there was an additional resource available that I could use when my course book needed a helping hand … or I did(!)

Yep, what I meant is, instead of trying to find tips, tricks and "cheat sheets" to learn C (as you were maybe implying, and also as some here seemed to even suggest!), just properly learn the language.
My comment was related to one of my posts in another thread about C and how it's often not learned/taught properly compared to other languages. So, I'm just hoping you will do it right. :)

Of course, the K&R book (best use latest edition) is an obvious start. Once you're done with that, and you're proficient enough, I also suggest reading the C standard to complement your knowledge in depth, especially to understand what could be undefined behaviors. The C99 standard is now easy to find online for free. Later versions less so, and buying them IS expensive. C11 adds a few niceties, but you can certainly do without it for the time being, and especially if you target programming on MCUs. I recommend writing C99-compliant code though. C99 adds a number of important new things, such as stdint.h, which defines standard types for integers of all supported widths, something important for portability, especially for embedded development. Earlier C versions relied on using implementation-dependent tricks to use integers of a specific width, which was frankly not pretty.

BTW books on C (e.g. The C Programming Language by Kernighan and Richie): do they cover any peculiarities (are there any) when using C in programming microcontrollers?

Not that I know of.
And any "peculiarities" would be documented in said MCUs' reference manuals, or specific books, rather than in a generic book.
If you're going to use a modern, 32-bit MCU with for instance an ARM core or RISC-V, there is really no specificity in general, they pretty much look like any 32-bit CPU from the language POV.

Of course you'll need to know some additional things, like how to define interrupts for instance, but then read books and example code for your preferred platform. I'd suggest doing that AFTER you've learned enough C.


 
The following users thanked this post: Siwastaja

Offline PerranOakTopic starter

  • Frequent Contributor
  • **
  • Posts: 579
  • Country: gb
Re: C word
« Reply #18 on: September 13, 2019, 02:38:52 pm »
Excellent, thanks mate. I did OK with learning assembly so I'll do my best to learn it well.
You can release yourself but the only way to go is down!
RJD
 

Offline TK

  • Super Contributor
  • ***
  • Posts: 1724
  • Country: us
  • I am a Systems Analyst who plays with Electronics
Re: C word
« Reply #19 on: September 13, 2019, 03:02:10 pm »
No wonder why there is so much confusion to learn C today... too much misinformation, oversimplification... when I started with C, there was only one reference: K&R C Programming Language book.
 

Offline xrunner

  • Super Contributor
  • ***
  • Posts: 7938
  • Country: us
  • hp>Agilent>Keysight>???
Re: C word
« Reply #20 on: September 13, 2019, 03:05:54 pm »
No wonder why there is so much confusion to learn C today... too much misinformation, oversimplification... when I started with C, there was only one reference: K&R C Programming Language book.

Same here - still have it too.  :)
I told my friends I could teach them to be funny, but they all just laughed at me.
 

Offline janoc

  • Super Contributor
  • ***
  • Posts: 3958
  • Country: de
Re: C word
« Reply #21 on: September 13, 2019, 03:09:54 pm »
On top of that there are issues that will not be a problem if someone already knows the language and uses the list as a cheatsheet, but if someone wants to learn from it, there are a few more catches:
  • The sizes for integers are the minimum requirements, not the actual values — yet there is no mention of that.

That's quite an interesting 'gotcha' for embedded programmers.


No only embedded - there are tons of programmers that assume that int is 32bits or that pointers are 32bits (yes, still!). Then surprises happen.


Not so long ago I was caught out writing an SPI driver for an STM32F7.

This particular device has a feature called 'packed writes' (or something along those lines). The way it works is:

- if you perform an 8-bit write to the SPI data register, it clocks out 8 bits.
- if you perform a 16 (or more) bit write to that exact same register, it clocks out 16 bits.

You've probably already guessed the problem - the driver inserted '0' bytes in between each data byte, because the compiled code used a 32-bit write instruction to copy each individual byte into the data register, and the hardware dutifully interpreted this as a 'packed' write, 16 bits wide, with bits 8..15 = 0.

Needless to say, it took a while to find that one, and a while longer to work out where exactly I needed to add (uint8_t) to force an 8-bit write.

I got caught by this too, I think most STM32s do this and not only for SPI. I had this bug with I2C on STM32F0, if I remember right.
 

Offline rstofer

  • Super Contributor
  • ***
  • Posts: 10088
  • Country: us
Re: C word
« Reply #22 on: September 13, 2019, 03:34:30 pm »
BTW books on C (e.g. The C Programming Language by Kernighan and Richie): do they cover any peculiarities (are there any) when using C in programming microcontrollers?

There are various documents scattered around the Internet but there's a problem.  When they show a peculiarity, the newcomer won't even understand the question, much less the answer.  These oddities are in the 'corners' of the language and you can spend a lot of time writing code and never bump into them.  This is particularly true in embedded programming where we're not trying to use C to solve world hunger.

What K&R does is serve as an example of good code without going exotic.  I like to steal the string and conversion functions from the original book and use them in my embedded work.  Why such old code?  It doesn't require a heap and I really don't like heaps colliding with stacks in limited memory uCs.

There are a few pitfalls here

https://pmihaylov.com/macros-in-c/

Pay attention toe Pitfall 1, it will jump up and bite you in the butt.

Like most things, C is best learned by practice and mistakes.  As each mistake is diagnosed, it adds to experience.  It is naive to think that there is a single book, somewhere, that will turn the newcomer into a wizard by just placing it under the pillow at night.  This stuff takes time and effort.



 

Offline rstofer

  • Super Contributor
  • ***
  • Posts: 10088
  • Country: us
Re: C word
« Reply #23 on: September 13, 2019, 04:01:31 pm »
How about the local community college?  Ours has an EXCELLENT lower division curriculum.  How telling that the first language they introduce is Pascal.  Learn with an excellent language before moving on to C/C++ or Java.  Sometimes community college scheduling works out with  having a paying job, other times, not so much.
 

Online SiliconWizard

  • Super Contributor
  • ***
  • Posts: 17782
  • Country: fr
Re: C word
« Reply #24 on: September 13, 2019, 04:12:37 pm »
Learn with an excellent language before moving on to C/C++ or Java.

Oh, I really agree with this.

And for those that are still impatient to move on to embedded dev, they could look at Ultibo. That's Pascal for bare-metal programming of RPis...
(see there: https://www.eevblog.com/forum/embedded-computing/ultibo-bare-metal-programming-rpis/  ;D )
 
The following users thanked this post: boz


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf