NO

Author Topic: Using sizeof on VLAs gives an incorrect warning.  (Read 2226 times)

neo313

  • Guest
Using sizeof on VLAs gives an incorrect warning.
« on: July 16, 2014, 02:51:15 PM »
Using sizeof operator on variable-length arrays gives an incorrect Expression with no effect removed. warning.

Code: [Select]

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int main( void )
{
const size_t size = 12 ;
char a[size] ;     //warnings are not present if size is constant: char a[12] ;

size_t a_size = sizeof( a ) ;

int n = snprintf( a , a_size , "Copy text ABCDEFG." ) ;
printf("%s\n%d\n" , a , n ) ;


n = snprintf( a , sizeof( a ) , "Copy text ABCDEFG." ) ;
printf("%s\n%d\n" , a , n ) ;

printf( "%zu" , sizeof( a ) ) ;

return 0 ;
}

Gives warnings:
main.c(11): warning #2046: Expression with no effect removed.
main.c(17): warning #2046: Expression with no effect removed.
main.c(20): warning #2046: Expression with no effect removed.

Level 2 warnings must be used. Optimization or other project options don't have any effect. I get this result on 32bit RC5 and RC4 version.
« Last Edit: July 16, 2014, 05:35:50 PM by neo313 »

Offline frankie

  • Global Moderator
  • Member
  • *****
  • Posts: 2113
Re: Using sizeof on VLAs gives an incorrect warning.
« Reply #1 on: July 16, 2014, 05:00:50 PM »
It seems a compiler development debug info promoted to warning.
Substantially it advices that the compiler doesn't need to use the sizeof operator because the size is in a variable, when it is declared as static size the compiler must use the sizeof operator to retrieve the size ...  :(
If you look to assembly in debug you will see that in the first case it uses the content of variable 'size' as array size, in the other case it uses a constant value presumably coming from the internal sizeof operation.
"It is better to be hated for what you are than to be loved for what you are not." - Andre Gide

Offline Pelle

  • Administrator
  • Member
  • *****
  • Posts: 2266
    • http://www.smorgasbordet.com
Re: Using sizeof on VLAs gives an incorrect warning.
« Reply #2 on: July 17, 2014, 10:19:03 AM »
For a VLA, any side-effects of the *runtime* expression must be evaluated. The compiler function removing expressions without side-effects can either be silent or issue warnings. In this case the quick fix is to use the silent mode (and possibly teaching that function new tricks in the future).
/Pelle