Author Topic: C data len  (Read 3690 times)

0 Members and 1 Guest are viewing this topic.

Offline DiTBhoTopic starter

  • Super Contributor
  • ***
  • Posts: 3915
  • Country: gb
C data len
« on: May 28, 2022, 11:49:13 am »
Code: [Select]
    unsigned int  data_size = 32;
    unsigned char data[data_size];
    unsigned int  sense_len = 256;
    unsigned char sense[sense_len];

This code doesn't compile on a couple of C compilers { SierraCC, Avget68kCC, AtlasMIPSCC, ... }
It works on Gcc -v4.1.2 ... Gcc -v11.0

isn't bad idea to define the size of array this way?
The opposite of courage is not cowardice, it is conformity. Even a dead fish can go with the flow
 

Offline nctnico

  • Super Contributor
  • ***
  • Posts: 26906
  • Country: nl
    • NCT Developments
Re: C data len
« Reply #1 on: May 28, 2022, 11:57:09 am »
It is not a bad idea at all since you don't have to clean it up afterwards / use dynamic memory allocation. However this wasn't in the original C specification so some compiler may not support it with the default settings. Check the manuals & command line options that have to do with what C standard the compiler is set to.
There are small lies, big lies and then there is what is on the screen of your oscilloscope.
 

Offline DC1MC

  • Super Contributor
  • ***
  • Posts: 1882
  • Country: de
 

Offline DiTBhoTopic starter

  • Super Contributor
  • ***
  • Posts: 3915
  • Country: gb
Re: C data len
« Reply #3 on: May 28, 2022, 12:10:20 pm »
It is not a bad idea at all since you don't have to clean it up afterwards / use dynamic memory allocation.

I prefer this approach
Code: [Select]
#define data_SIZE xxxx
data_t data[data_SIZE];
size_t data_size = data_SIZE;

this way, it works on all my C compilers, including the old one used by IDT for their MIPSR2K prototypes (~1995).
The opposite of courage is not cowardice, it is conformity. Even a dead fish can go with the flow
 

Offline DC1MC

  • Super Contributor
  • ***
  • Posts: 1882
  • Country: de
Re: C data len
« Reply #4 on: May 28, 2022, 12:12:57 pm »
It is not a bad idea at all since you don't have to clean it up afterwards / use dynamic memory allocation.

I prefer this approach
Code: [Select]
#define data_SIZE xxxx
data_t data[data_SIZE];
size_t data_size = data_SIZE;

this way, it works on all my C compilers, including the old one used by IDT for their MIPSR2K prototypes (~1995).

You know that you could have made the size initializer a constant ?  :palm:
 

Offline DiTBhoTopic starter

  • Super Contributor
  • ***
  • Posts: 3915
  • Country: gb
Re: C data len
« Reply #5 on: May 28, 2022, 12:25:15 pm »
Variable length arrays are a problem for my ICEs because they don't understand the size, especially  when the array size depends on a function parameter

Code: [Select]
void fun(int n)
{
 int arr[n]; // <--------- the ICE here thinks WTF?!? is the size of arr?!?
 // ......

int main()
{
  fun(6);
}

Gcc v4.1.2 is very old and does not complain, while the above code does nothing but trigger errors on both the C compiler and ICE with the code completely rejected!

runtime sized array are bad for automated ICE-debugging, at least for me  :-//
The opposite of courage is not cowardice, it is conformity. Even a dead fish can go with the flow
 

Offline DiTBhoTopic starter

  • Super Contributor
  • ***
  • Posts: 3915
  • Country: gb
Re: C data len
« Reply #6 on: May 28, 2022, 12:38:30 pm »
You know that you could have made the size initializer a constant ?  :palm:

umm, yeah, at least Gcc triggers warnings and errors if you try to modify something defined as constant ... it's just that the keyworkd "const" is ignored by my ICE, so making the size of the initializer a constant is useful like sweeping leaves on the street on a windy day  :-//



The opposite of courage is not cowardice, it is conformity. Even a dead fish can go with the flow
 

Offline Jeroen3

  • Super Contributor
  • ***
  • Posts: 4078
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: C data len
« Reply #7 on: May 28, 2022, 01:28:25 pm »
Code: [Select]
    const unsigned int  data_size = 32;
    unsigned char data[data_size];
    const unsigned int  sense_len = 256;
    unsigned char sense[sense_len];
Now it will.
 

Offline magic

  • Super Contributor
  • ***
  • Posts: 6779
  • Country: pl
Re: C data len
« Reply #8 on: May 28, 2022, 03:06:35 pm »
Only C++ constexpr can be used to specify array dimensions. The usual C solution is #define.

Inside function scope a VLA will be created and then data_size doesn't need to be const, you could even use atoi(argv[1]) instead. If this doesn't work then your compiler isn't C99 compliant.

VLAs consume stack space :--
 

Online SiliconWizard

  • Super Contributor
  • ***
  • Posts: 14475
  • Country: fr
Re: C data len
« Reply #9 on: May 28, 2022, 05:21:11 pm »
I don't even understand how the code you posted compiles with GCC.
I tried both with GCC 10.3 and GCC 12, and it fails in both cases with an error: "variably modified 'data' at file scope".

But of course you need to put context here.
If the code you posted is at file scope (global context), then it's an error even in C99+.
If it's in local scope, then it's a VLA, and is only supported by a C99+-compliant compiler. If that's what you were doing, I suppose the compilers you mention are not compliant with C99.
And yes, as I think was mentioned about VLAs not too long ago, even with a const qualifier for the size variable in local scope, this will yield a VLA. That's just C. If you don't want VLAs, just use a macro. You have no choice.
« Last Edit: May 28, 2022, 05:23:58 pm by SiliconWizard »
 
The following users thanked this post: newbrain

Offline TheCalligrapher

  • Regular Contributor
  • *
  • Posts: 151
  • Country: us
Re: C data len
« Reply #10 on: May 29, 2022, 09:05:45 am »
C is a bit more limited than C++ with respect to dimensioning arrays.
You can create a VLA ( Variable-length array ) with dynamic size, or you can create
an array of either zero (special cases) or fixed dimensions.

Er... That makes C a bit less limited with respect to dimensioning arrays. Less, not more. C++ is more limited, since C++ does not support VLA.

It is perhaps unfortunate that one can't use an expression which involves a static or global const variable whose constant initializer value is known to the compiler at the time of the array definition to also dimension the array by a shared indirect "constant" expression value.

It is completely not clear what it is supposed to mean. Yes, you can do all that as long as your C compiler supports VLA and the array is local.

In C++ one can use constexpr values as array dimensions more freely than the plain "const" values which are comparable in both C and C++.

That is completely incorrect. `const` values are very different in C and C++.

`constexpr` variables do not add anything over `const` in C++. They simply help user to express their intent (and the compiler to enforce that intent).

 
The following users thanked this post: DiTBho

Offline TheCalligrapher

  • Regular Contributor
  • *
  • Posts: 151
  • Country: us
Re: C data len
« Reply #11 on: May 29, 2022, 09:08:41 am »
VLAs consume stack space :--

All local arrays and all local variables consume stack space. VLA does not stand out in any way, unless you do something really stupid.

Are local variables :-- ?
 

Offline magic

  • Super Contributor
  • ***
  • Posts: 6779
  • Country: pl
Re: C data len
« Reply #12 on: May 29, 2022, 09:26:44 am »
Local arrays are unique in being stack allocated AND having the potential to eat up a lot of space, which is often in short supply in places where C is used. Even Linux processes are limited to 8MB stack by default.

(Also, local variables can exist solely in CPU registers ;))
 

Online SiliconWizard

  • Super Contributor
  • ***
  • Posts: 14475
  • Country: fr
Re: C data len
« Reply #13 on: May 29, 2022, 06:49:28 pm »
This discussion about VLAs is potentially endless a bit like the one about electricity. :-DD

As TheCalligrapher just said, there is no difference with any other object allocated on the stack.
The only difference, sure, is that VLAs can potentially eat up a lot of stack space if the programmer doesn't know what they are doing. In which case, they can do a lot of damage elsewhere too. Again yet another endless "discussion" about C in general, I guess.

You're assuming VLAs are "bad" because they can allocate "too much space" on the stack, but it's like seeing only one side of things while ignoring the rest.
Indeed, OTOH, a potential benefit of VLAs is precisely that you don't need to allocate a fixed-size array (and thus with the max size required in all cases) on the stack in a given context, but can allocate what is just necessary at run-time, actually yielding a more reasoned use of stack space.
 

Offline DavidAlfa

  • Super Contributor
  • ***
  • Posts: 5907
  • Country: es
Re: C data len
« Reply #14 on: June 02, 2022, 02:41:42 am »
Although you're initializating the variable, it's still a ram variable, could change anytime, that's what the compiler sees, while value of a variable declaration must be constant.
Options are this:
Code: [Select]
    const unsigned int  data_size = 32;
    unsigned char data[data_size];
    const unsigned int  sense_len = 256;
    unsigned char sense[sense_len];
Or:
Code: [Select]
    #define data_size 32
    unsigned char data[data_size];
    #define sense_len 256
    unsigned char sense[sense_len];
Hantek DSO2x1x            Drive        FAQ          DON'T BUY HANTEK! (Aka HALF-MADE)
Stm32 Soldering FW      Forum      Github      Donate
 

Online IanB

  • Super Contributor
  • ***
  • Posts: 11891
  • Country: us
Re: C data len
« Reply #15 on: June 02, 2022, 04:24:41 am »
Although you're initializating the variable, it's still a ram variable, could change anytime, that's what the compiler sees, while value of a variable declaration must be constant.
Options are this:
Code: [Select]
    const unsigned int  data_size = 32;
    unsigned char data[data_size];
    const unsigned int  sense_len = 256;
    unsigned char sense[sense_len];

According to the post above yours, this is not valid in C if the array size needs to be statically defined at compile time. The one with #define is OK, though.
 
The following users thanked this post: magic, DavidAlfa

Offline DavidAlfa

  • Super Contributor
  • ***
  • Posts: 5907
  • Country: es
Re: C data len
« Reply #16 on: June 02, 2022, 08:25:12 am »
Why? Size is declared as const. The compiler knows that.
It compiles right away without any warning.
In the instant you remove const - error!
Hantek DSO2x1x            Drive        FAQ          DON'T BUY HANTEK! (Aka HALF-MADE)
Stm32 Soldering FW      Forum      Github      Donate
 

Offline Jeroen3

  • Super Contributor
  • ***
  • Posts: 4078
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: C data len
« Reply #17 on: June 02, 2022, 11:07:01 am »
It appears some compilers behave non-standard when given an const integer as array declarator expression.
I don't remember ever hitting this, but apparently the pure environment of godbolt does show it.

Looks like if you don't want to use the preprocessor you can use enums.
 

Offline DiTBhoTopic starter

  • Super Contributor
  • ***
  • Posts: 3915
  • Country: gb
Re: C data len
« Reply #18 on: June 02, 2022, 11:27:04 am »
It appears some compilers behave non-standard when given an const integer as array declarator expression.

Yup, precisely. AvgetCC is an example.
Also my ICE doesn't correctly understand "const", hence its parser is set to ignore (skip token).

I don't use "const" in none of my projects.

Even if you look at the source code of big and complex projects like the firmware of my industrial embroidery machine, you won't find any "const".

"const" is banned from my C-coding style, and I tend to use the linker_script to specifically allocate constant variables in the RO session, hence again, I don't need "const".


---

Anyway, yesterday I rewrote the whole C source in a clean way.
No more "const", no more "VLA". Thins are clean, debugged through an automatic test-case plan, all is fine like it should be.

For me: VLA is banned from my C-coding style.


( I am a weird C programmer, I know  :o :o :o )
The opposite of courage is not cowardice, it is conformity. Even a dead fish can go with the flow
 

Offline thinkfat

  • Supporter
  • ****
  • Posts: 2152
  • Country: de
  • This is just a hobby I spend too much time on.
    • Matthias' Hackerstübchen
Re: C data len
« Reply #19 on: June 02, 2022, 11:35:42 am »
Have a look at the below link;
it fails with an error on gcc, though clang passes it with a warning that it allowed it as an extension:
https://godbolt.org/z/3fPhnhYTz

That is a handy site because one can easily try most common compilers / platforms / compilation options and see what
a snipped of code compiles to or if it compiles without errors / warnings at all.

That's for a static storage version of your suggested 'const' code.
If the storage wasn't specified to be static then the 'const' wouldn't matter since
one can create VLAs even with dynamic lengths no problem so of course a const dimension would also have worked
to create a VLA.   So if that's the aim then no problem.  But it isn't a general solution for creating
truly 'const' global / extern / static data arrays of constant dimension and initialization such as one
could commonly have linked to be placed in FLASH / ROM / RODATA etc. instead of living on the RAM stack.

Don't use "static", then. VLA's cannot be static. They're then not on the stack but in the BSS or DATA segment and that just cannot work.
Everybody likes gadgets. Until they try to make them.
 

Offline Jeroen3

  • Super Contributor
  • ***
  • Posts: 4078
  • Country: nl
  • Embedded Engineer
    • jeroen3.nl
Re: C data len
« Reply #20 on: June 02, 2022, 11:49:11 am »
...
"const" is banned from my C-coding style, and I tend to use the linker_script to specifically allocate constant variables in the RO session, hence again, I don't need "const".
...
const should still be used to indicate design intent. It will still function as operator that values are immutable, which is valueable in my opinion.
For example, both variants of const pointers (const ptr and ptr to const), and factors for calculations should be const.
It also enforces types on your values, define does not. Something to aware of.
 

Offline newbrain

  • Super Contributor
  • ***
  • Posts: 1719
  • Country: se
Re: C data len
« Reply #21 on: June 02, 2022, 02:09:23 pm »
Why? Size is declared as const. The compiler knows that.
It compiles right away without any warning.
In the instant you remove const - error!
Well, simply because that's not C - if the declaration has static storage duration (e.g. file scope).
If the compiler swallows it without complaining, then it's not being used as a C compiler.

See C11, 6.7.6.2, §2.

That the const value of the int is known at compile time is immaterial, that's not the way the language is defined:
gcc and clang will by default compile a language which  is "almost, but not quite, entirely unlike C" (cit.).
If you want to coax them to be C compilers, -std=C11 -Wall -Wextra -pedantic is needed (for C11 - change to your favourite flavour).

But rejoice, it's still valid C++! Though there are no VLA in C++, and const semantic is slightly different.
Nandemo wa shiranai wa yo, shitteru koto dake.
 
The following users thanked this post: DiTBho

Online SiliconWizard

  • Super Contributor
  • ***
  • Posts: 14475
  • Country: fr
Re: C data len
« Reply #22 on: June 02, 2022, 05:41:05 pm »
And, as already pointed out here and in other threads, in C99+, using a variable as size in the declaration of an array is forbidden in file scope (so non-local context), and makes the array a VLA de-facto in local context, whether the variable itself is qualified const or not. Doesn't matter.

That said, as I think I also showed in another thread, if optimizations are enabled and the compiler is not brain-dead, if the value of said variable is effectively a constant in its scope (whether it's qualified const or not), then the actual compiled code will be that of a regular array and not that of a VLA. Now disable optimizations, and you'll get code for a VLA even when the size variable is statically analyzed as being constant in its scope. And compiled as a VLA means significant overhead manipulating the stack. But just see for yourself looking at assembly code and trying various code combinations and optimization levels.
 

Offline newbrain

  • Super Contributor
  • ***
  • Posts: 1719
  • Country: se
Re: C data len
« Reply #23 on: June 02, 2022, 09:53:40 pm »
But just see for yourself looking at assembly code and trying various code combinations and optimization levels.
Or just write C - for me, at least, it's easier: as opposed to the compilateur du jour, the standard stays mostly put, and compliance of the usual suspects is pretty good, when dutifully instructed.

Quote
I rewrote the whole C source in a clean way.
No more "const",
I think you misspelled "less safe" - I know, I know, your ICE will melt if you use const. ::)


Nandemo wa shiranai wa yo, shitteru koto dake.
 
The following users thanked this post: Siwastaja

Offline DiTBhoTopic starter

  • Super Contributor
  • ***
  • Posts: 3915
  • Country: gb
Re: C data len
« Reply #24 on: June 02, 2022, 11:18:00 pm »
I think you misspelled "less safe"

Our ICE better understands _RO suffix in the variable name, so it can be checked automatically and without the need to query for the definition. It requires less memory in the local ICE database, is literally one less token, generates fewer queries between the ICE and the host, and is easier for both the local AI and the human operator to check than a distant word "const" which no one, except the C(1) compiler, will examine.


(1) sometimes misunderstanding it, like AvogetCC does. Incredible that we paid ~6K euros for it in 2001, and Off course, VLA is not supported.
The opposite of courage is not cowardice, it is conformity. Even a dead fish can go with the flow
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf