Nios® V/II Embedded Design Suite (EDS)
Support for Embedded Development Tools, Processors (SoCs and Nios® V/II processor), Embedded Development Suites (EDSs), Boot and Configuration, Operating Systems, C and C++
Announcements
FPGA community forums and blogs on community.intel.com are migrating to the new Altera Community and are read-only. For urgent support needs during this transition, please visit the FPGA Design Resources page or contact an Altera Authorized Distributor.
12748 Discussions

Curious compiler error, "j=j++"

Altera_Forum
Honored Contributor II
1,135 Views

Hey, I made an error coding yesterday while developing an application for the NIOS II processor. I accidentally typed "j=j++;" instead of just "j++;". What I found curious was the resulting assembly: 

 

 

<div class='quotetop'>QUOTE </div> 

--- Quote Start ---  

gcc version 3.4.1 (Altera Nios II 6.1 b197) 

 

j=j++; 

 

0x00102bb0 <process_packet+940>:  addi  r3,fp,60 

0x00102bb4 <process_packet+944>:  ldw  r2,0(r3) 

0x00102bb8 <process_packet+948>:  mov  r4,r2 

0x00102bbc <process_packet+952>:  addi  r2,r2,1 

0x00102bc0 <process_packet+956>:  stw  r2,0(r3) 

0x00102bc4 <process_packet+960>:  stw  r4,60(fp)[/b] 

--- Quote End ---  

 

 

I don&#39;t mind so much that j doesn&#39;t get incremented, j=j++ is a quirky case, but why two memory writes? I compiled the code using the default options associated with the "hello world stand alone" template. 

 

--Jordan
0 Kudos
1 Reply
Altera_Forum
Honored Contributor II
407 Views

I wrote the following function: 

 

void TestCompiler2(int j) {   j = j++; } 

 

and upon compiling received this warning message: 

 

../hello_world_small.c: In function `TestCompiler2&#39;: 

../hello_world_small.c:189: warning: operation on `j&#39; may be undefined 

 

I have all warnings enabled, and for my real projects I have -Wall and -Werror on the compiler flags line (with the -Wall checkbox off, as it can override values on the compiler flags line). 

 

Here is the produced code, built with the release configuration: 

 

010002b4 <TestCompiler2>: 10002b4:    f800283a  ret 

 

So, to answer your question, you&#39;re building the debug version where the compiler is supposed to produce code that does literally what you are telling it to do. 

 

What you are telling it to do, is the following: 

 

1. Set j = to j. 

2. At some point, either before or after, increment j. 

 

The behavior is undefined according to the C standard because j is modified twice in the same expression. The compiler is free to perform the side-effect (incrementing j) at any time, although it must of course assign the previous value to whatever is to the left of the =. But because j is there, the behavior is undefined and the C compiler is allowed to do *anything* at this point, whether it makes sense or not.
0 Kudos
Reply