Skip to content

New dialect flag: -farray-parameters-are-const #151526

@alejandro-colomar

Description

@alejandro-colomar

This would change the dialect to make array parameters implicitly const.

The following code:

	int
	foo(int size, char buf[100], pid_t pid)
	{
		if (stprintf(buf, _Countof(buf), "/proc/%d/", pid) == -1)
			return -1;
		...
		return 0;
	}

would be equivalent to

	int
	foo(int size, char buf[const 100], pid_t pid)
	{
		if (stprintf(buf, _Countof(buf), "/proc/%d/", pid) == -1)
			return -1;
		...
		return 0;
	}

This would allow one to safely use _Countof() with array parameters, without the pointer being advanced accidentally, which would turn the size information outdated.

We can't make this the default behavior, as it would break existing code, but programmers might want to change the behavior in their own programs (I do). That would make it so that we don't need to write const in every array parameter to be able to use _Countof() on them. (I've written a proposal for extending _Countof() to work on array parameters, and a constraint would be that they need to be const-qualified.)

It is also morally appropriate, as these pointers represent arrays (even if they are not), so it wouldn't make sense to try to modify the address.

This closes part of the gap between array parameters and arrays.

See GCC proposal: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=121271

See standard proposal (draft): https://www.alejandro-colomar.es/src/alx/alx/wg14/alx-0056.git/

Cc: @AaronBallman

Related: #150953

Metadata

Metadata

Assignees

No one assigned

    Labels

    cclang:frontendLanguage frontend issues, e.g. anything involving "Sema"enhancementImproving things as opposed to bug fixing, e.g. new or missing feature

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions