26

Some time ago I stumbled upon the idea of how a C construct, such as (expr0, expr1, expr2), evaluates (see "What does the comma operator , do?" for more context).

I've started experimenting with this, especially inside of function-like macros, and recently found a code which is rejected by some compilers, while accepted by others. It looks similar to the following snippet:

#include <stdio.h>

int main(void)
{
    int arr[] = {0};
    (1, arr[0]) = 30;  // <--- potentially (in)valid code
    printf("%d\n", arr[0]);
    return 0;
}

As you can see, in order for this to work, (1, arr[0]) must be evaluated to lvalue arr[0], otherwise assignment would NOT be possible. However, I'm not sure if said behavior is valid or not. It "makes sense" and I found a use for it, but I also see why compiler devs would reject it.

The code above is rejected by gcc, clang and msvc (note that msvc is primarily a C++ compiler, while gcc and clang are C front-ends):

$ gcc main.c
main.c: In function ‘main’:
main.c:6:21: error: lvalue required as left operand of assignment
    6 |         (1, arr[0]) = 30;
      |                     ^

$ clang main.c -Wno-unused-value
main.c:6:14: error: expression is not assignable
    6 |         (1, arr[0]) = 30;
      |         ~~~~~~~~~~~ ^
1 error generated.

$ cl main.c /nologo
main.c
main.c(6): error C2106: '=': left operand must be l-value

For comparison, g++, clang++ and tcc are fine with said code (note that tcc is a C compiler, while g++ and clang++ are C++ front-ends):

$ tcc main.c && ./a.out
30

$ g++ main.c && ./a.out
30

$ clang++ main.c -Wno-unused-value -Wno-deprecated && ./out
30

I also tried with some different command options, such as explicitly setting msvc to running in either /std:c++latest and /std:c99 modes, or by setting different -std for gcc/clang/g++/clang++ but it did not change anything.

At first, I thought it's a bug within tcc, since it's the only C compiler which does not reject the "faulty" code, but then I checked C++ front-ends and I'm not so sure about it any more. Especially since msvc rejects it unlike g++/clang++.

  • Is the code I just presented a valid C, or C++, or both/neither?
  • Are C/C++ standards describing what should happen here?
  • Which compilers are right/wrong here? (tcc and msvc seems very odd)

For reference, I'm on x86_64 Linux, using gcc/g++ 14.2.1, clang 18.1.8, msvc 19.40.33811 (running through wine), and tcc 0.9.28rc (mob@08a4c52d).

10
  • 5
    Re: "It 'makes sense' and I found a use for it": OK, I have to know: what use did you find for it??
    – ruakh
    Commented Nov 8 at 23:36
  • 3
    @ruakh It was a generic implementation of dynamic array. I wanted to do some bound checking before returning the lvalue from function-like macro. Something like: #define ARR_AT(ARR, IDX) assert((ARR)._len > 0 && (IDX) < (ARR)._len), (ARR)._data[(IDX)]) so I could do: ARR_AT(arr, 0) = 30. Yea, I know it's messy, but I was just experimenting. It seems like a valid use-case though. Commented Nov 8 at 23:49
  • 6
    @Gene: If the macro expanded to multiple statements, if (foo) ARR_AT(arr, 0) = 30; would make the assert conditional, the assignment unconditional. Except in an NDEBUG build, creating a heisenbug. It would also prevent ARR_AT from being an operand to function calls like bar(1, 2, ARR_AT(arr, i)). Commented Nov 9 at 16:42
  • 3
    @Gene: What's wrong with indexing a container as an argument to a function? This is exactly like indexing a std::vector with bounds-checking on, except in C with macros. Except unfortunately this hack only works in C++, where we could do the same thing better with a template function or a standard container. So in C the only recourse is a generic function, or a GNU C statement-expression using {assert(); (ARR)._data[IDX];} Commented Nov 9 at 22:36
  • 2
    There is no shame in using evil features while whole language is also evil >:) Commented Nov 10 at 1:33

3 Answers 3

32

In C, the code is not valid. As N3096 6.5.17 says,

Then the right operand is evaluated; the result has its type and value.129

Note 129 says:

A comma operator does not yield an lvalue.

So, it is a "non-lvalue" (i.e. r-value) and cannot be used as an l-value.

For C++, on the other hand, per [expr.comma]

The type and value of the result are the type and value of the right operand; the result is of the same value category as its right operand,

Since it's the same value category as the right operand, it would be an l-value and would be valid.


Note that your code compiles fine in MSVC as a C++ file. MSVC, or more specifically CL, will treat .c files as C, and .cpp files as C++ by default. See here where the left compiler is MSVC forced to compile as C code, and the right is MSVC compiling as C++

8
  • 8
    Also listed in [diff.expr]/4 as one of the intentional incompatible changes made by C++ (C++98) relative to C when it was standardized. Also has a nice example showing that this can change the semantics of a well-defined C program when compiled as C++. Commented Nov 8 at 23:56
  • @ChrisMM Re: "Note that your code compiles fine in MSVC as a C++ file" Ahhh, I see. Thank you. I thought setting /std:c++ would do the trick. Commented Nov 8 at 23:59
  • @sleeptightAnsiC, that just sets what standard to use. It doesn't tell it how to compile individual files.
    – ChrisMM
    Commented Nov 9 at 2:40
  • @user17732522, thanks, I missed that.
    – ChrisMM
    Commented Nov 9 at 2:41
  • 3
    @sleeptightAnsiC - There are options to override the file type, but they are /TC for C and /TP for C++. Usually a lot easier to change the extension.
    – BoP
    Commented Nov 9 at 9:07
13

For C: according to N3096 (PDF), § 6.3.2.1 paragraph 2 (page 48):

Except when it is the operand of the sizeof operator, or the typeof operators, the unary & operator, the ++ operator, the -- operator, or the left operand of the . operator or an assignment operator, an lvalue that does not have array type is converted to the value stored in the designated object (and is no longer an lvalue); this is called lvalue conversion.

In your example, arr[0] is an operand of the , operator, so should lose its lvalue-ness; so tcc is wrong, and the other C compilers are correct.

6
  • 1
    Thanks. I'll check tcc mailing list and send them bug report soon. Commented Nov 9 at 0:05
  • 3
    Got this reported here: lists.nongnu.org/archive/html/tinycc-devel/2024-11/… Commented Nov 9 at 14:29
  • Tcc is not wrong, it is just not strict enough and accepts this unambiguous expression as an extension, probably as an involuntary side effect :)
    – chqrlie
    Commented Nov 15 at 13:05
  • @chqrlie Why don't you concider it as a bug? Just like someone mentioned in one of the comment's, this can alter the behavior of the program, e.g. int arr[] = {0}; int val = sizeof (0, arr); in this case val will have a different value. Commented Nov 15 at 20:32
  • It would be a bug to behave differently than specified in the standard, but when the standard does not support a given construction, an implementation may define the behavior as an extension. Both gcc and clang do this for many other cases.
    – chqrlie
    Commented Nov 15 at 23:54
2

Your parenthesis is misplaced. (1,arr)[0] should work.

8
  • 5
    Actually... This answer is somehow useful to me (although it doesn't answer the question at all). Moving [0] outside of (..., ...) makes it possible to turn anything into lvalue which I haven't thought about. For example: when wrapping (funccall, pointer)[0] or *(funccall, pointer) with a macro. This would fix the exaple of ARR_AT(arr, 0) = 30 which I mentioned in one of the comments. Unironically, noone sugested this. Thanks :) Commented Nov 10 at 1:28
  • 5
    @sleeptightAnsiC I guess nobody suggested this as a solution because you didn't ask about arrays/pointers specifically, and this trick only works for arrays/pointers. Commented Nov 10 at 6:35
  • 2
    @sleeptightAnsiC Oh, I see: the (...) expression is not an lavalue in C, but it desn't have to be -- xx[0] is an lvalue even if xx is not, cool! (As an aside, in C you could also revert the operands for the [] operator, i.e. (1,0)[arr] should work. Because indexing is defined as addition, and addition is commutative, indexing is commutative as well, with the expected, well-defined results. That makes it obvious that the left operand does not have to be an lvalue at all.) Commented Nov 10 at 18:19
  • @Peter-ReinstateMonica: "Ordinary" addition would work with operands of matching types, but adding pointers to other pointers doesn't work.
    – supercat
    Commented Nov 10 at 23:47
  • 1
    Btw, this is how tcc keeps l-valueness on ternary operator — it just converts a ? b : c to *(a ? &b : &c) if possible.
    – wqw
    Commented Nov 15 at 11:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.