Ошибка iso c90 запрещает смешение деклараций и кода

When compiling in c, the compiler is giving me a warning telling me that C90 forbids mixing declaration and code, however their is no case of this in my code and the line that it says the warning occurs at is clearly just the declaration of a variable their is no code mixed with it.

This is what my compiler shows

gcc -c Functions.c -Wall -ansi -pedantic
Functions.c:27:18: warning: ISO C90 forbids mixing declarations and code
      [-Wdeclaration-after-statement]
        LinkedListNode* curr;
                        ^
1 warning generated.

This is my function where the warning is occurring

BLUEPIXY's user avatar

BLUEPIXY

39.7k7 gold badges33 silver badges71 bronze badges

asked Oct 25, 2017 at 21:21

Cameron's user avatar

7

In fact there is code inbetween your declarations, the offending line being arraySize = list->numElements. You can move that line further down, after LinkedListNode *curr declaration or merge it with the declaration of arraySize the line before, like this: int arraySize = list->numElements.

answered Oct 25, 2017 at 21:24

lukeg's user avatar

lukeglukeg

4,1893 gold badges19 silver badges40 bronze badges

I declared a variable in this way:

int i = 0;

I get the warning:

ISO C90 forbids mixed declarations and code

How can I fix it?

Peter Mortensen's user avatar

asked Nov 8, 2012 at 14:51

7

I think you should move the variable declaration to top of block. I.e.

{
    foo();
    int i = 0;
    bar();
}

to

{
    int i = 0;
    foo();
    bar();
}

answered Nov 8, 2012 at 14:53

Johan Kotlinski's user avatar

Johan KotlinskiJohan Kotlinski

25.2k9 gold badges78 silver badges101 bronze badges

4

Up until the C99 standard, all declarations had to come before any statements in a block:

void foo()
{
  int i, j;
  double k;
  char *c;

  // code

  if (c)
  {
    int m, n;

    // more code
  }
  // etc.
}

C99 allowed for mixing declarations and statements (like C++). Many compilers still default to C89, and some compilers (such as Microsoft’s) don’t support C99 at all.

So, you will need to do the following:

  1. Determine if your compiler supports C99 or later; if it does, configure it so that it’s compiling C99 instead of C89;

  2. If your compiler doesn’t support C99 or later, you will either need to find a different compiler that does support it, or rewrite your code so that all declarations come before any statements within the block.

answered Nov 8, 2012 at 16:22

John Bode's user avatar

John BodeJohn Bode

120k19 gold badges122 silver badges198 bronze badges

Just use a compiler (or provide it with the arguments it needs) such that it compiles for a more recent version of the C standard, C99 or C11. E.g for the GCC family of compilers that would be -std=c99.

2

Make sure the variable is on the top part of the block, and in case you compile it with -ansi-pedantic, make sure it looks like this:

function() {
    int i;
    i = 0;

    someCode();
}

Peter Mortensen's user avatar

answered May 9, 2013 at 9:05

Ron's user avatar

RonRon

1,7051 gold badge19 silver badges15 bronze badges

1

To diagnose what really triggers the error, I would first try to remove = 0

  • If the error is tripped, then most likely the declaration goes after the code.

  • If no error, then it may be related to a C-standard enforcement/compile flags OR …something else.

In any case, declare the variable in the beginning of the current scope. You may then initialize it separately. Indeed, if this variable deserves its own scope — delimit its definition in {}.

If the OP could clarify the context, then a more directed response would follow.

Peter Mortensen's user avatar

answered Nov 8, 2012 at 23:48

vmsnomad's user avatar

vmsnomadvmsnomad

3192 silver badges7 bronze badges

-Wdeclaration-after-statement minimal reproducible example

main.c

#!/usr/bin/env bash

set -eux

cat << EOF > main.c
#include <stdio.h>

int main(void) {
    puts("hello");
    int a = 1;
    printf("%d\n", a);
    return 0;
}
EOF

Give warning:

gcc -std=c89 -Wdeclaration-after-statement -Werror main.c
gcc -std=c99 -Wdeclaration-after-statement -Werror main.c
gcc -std=c89 -pedantic -Werror main.c

Don’t give warning:

gcc -std=c89 -pedantic -Wno-declaration-after-statement -Werror main.c
gcc -std=c89 -Wno-declaration-after-statement -Werror main.c
gcc -std=c99 -pedantic -Werror main.c
gcc -std=c89 -Wall -Wextra -Werror main.c
# https://stackoverflow.com/questions/14737104/what-is-the-default-c-mode-for-the-current-gcc-especially-on-ubuntu/53063656#53063656
gcc -pedantic -Werror main.c

The warning:

main.c: In function ‘main’:
main.c:5:5: warning: ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]
     int a = 1;
     ^~~

Tested on Ubuntu 16.04, GCC 6.4.0.

answered Oct 30, 2018 at 12:16

Ciro Santilli OurBigBook.com's user avatar

Ensure you made your declarations before any statements in the block.
For instance:

{
int i = 0;
printf("a string");/*the code is not a working code*/
}

I believe this should be helpful:

https://www.configrouter.com/iso-c90-forbids-mixed-declarations-and-code-in-c-30621/

answered Sep 30, 2022 at 18:01

Hilda Enyioko's user avatar

1

Я использую следующие флаги (где cc — это gcc 4.2 или clang 8.0):

$ cc -Wall -Werror -pedantic -ansi -std=c89 main.c

(Я знаю, что флаг -ansi в этом случае немного избыточен)

Следующее дает мне ожидаемую ошибку

main.c:31:8: warning: ISO C90 forbids mixing declarations and code [-Wdeclaration-after-statement]
  vec3 abc = {0};
int main()
{
  vec3 a = {0};
  vec3 b = {0};

  Vec3(2, 2, 2);

  vec3 abc = {0}; // Declared after a function call

  return 0;
}

Тем не менее, следующее не

int main()
{
  vec3 a = Vec3(0, 1, 2);
  vec3 b = Vec3(0, 1, 2);

  vec3 abc = {0}; // Declared after a function call

  return 0;
}

Конечно, инициализация переменной с помощью функции все еще считается смешиванием объявлений и кода?

Функция Vec3 очень проста; встроенный флаг не установлен и т. д.

vec3 Vec3(float x, float y, float z)
{
  vec3 rtn = {0};

  rtn.x = x;
  rtn.y = y;
  rtn.z = z;

  return rtn;
}

3 ответа

Лучший ответ

В этом фрагменте кода

  vec3 a = Vec3(0, 1, 2);
  vec3 b = Vec3(0, 1, 2);

  vec3 abc = {0}; // Declared after a function call

Есть только декларации. Там нет никаких заявлений. Вызовы функций, используемые для инициализации переменных, являются выражениями. Это не заявления.

Похоже это предупреждение

предупреждение: ISO C90 запрещает смешивать декларации и код

Сбивает с толку. Правильнее было бы написать, что

предупреждение: ISO C90 запрещает смешивать декларации и заявления

Например, даже избыточная точка с запятой вводит нулевое выражение. Поэтому в общем случае компилятор должен выдавать предупреждение даже для следующего фрагмента кода

  vec3 a = Vec3(0, 1, 2);;
                       ^^^^
  vec3 b = Vec3(0, 1, 2);


9

Vlad from Moscow
26 Ноя 2019 в 19:08

Вторая функция имеет три последовательных определения переменных с инициализаторами — это не проблема.

Что не позволяет C90 (C89), так это объявление после оператора — в данном блоке операторов (между { и }) все объявления должны предшествовать любым операторам (не-объявлениям). Простой вызов функции, не являющийся частью инициализатора, является оператором.

Вот почему GCC сообщает о проблеме -Wdeclaration-after-statement.


5

Jonathan Leffler
26 Ноя 2019 в 11:59

Вы неправильно понимаете ограничение. У нас могут быть объявления с инициализаторами; первый оператор без объявления отмечает конец объявлений, и после этого нам не разрешено больше объявлений в этой области.

Необъявленные операторы могут быть выражениями-выражениями (как указано выше), составными выражениями (такими как if или while) или блоками.


3

Toby Speight
26 Ноя 2019 в 11:59

make -C /lib/modules/2.6.36.4/build M=/home/zaffer/linux modules
make[1]: Entering directory `/usr/src/linux-2.6.36.4′
CC [M] /home/zaffer/linux/lko.o
/home/zaffer/linux/lko.c: In function ‘start’:
/home/zaffer/linux/lko.c:36:10: warning: ISO C90 forbids mixed declarations and code// WAT IS THE ABOVE LINE?……….//…………#######
Building modules, stage 2.
MODPOST 1 modules
WARNING: “scull_open” [/home/zaffer/linux/lko.ko] undefined!
CC /home/zaffer/linux/lko.mod.o
LD [M] /home/zaffer/linux/lko.ko
make[1]: Leaving directory `/usr/src/linux-2.6.36.4′

HEADER FILE
#include
#include
#include
#include
#include
#include
#include

#define SCULL_MAJOR 0

#define SCULL_MINOR 0

#define device_name “ZAFFER”

#define device_no 1

#define NO_OF_DEVICES 1

#ifndef DEBUG
#define DEBUG
#endif

//………………defining file_operations……………

int scull_open(struct inode*,struct file*);
//int scullrelease(struct inode*, struct file* );

//……………….end of functions…………………..

//…………………….major mainor…………………

static int scull_major = SCULL_MAJOR;
static int scull_minor = SCULL_MINOR;
//………….. ……………………….
//……………….structs and declerations…………..
const struct file_operations fops={
.open = scull_open,
// release: scullrelease
};
struct Scull_dev{

struct cdev cdev;

};
struct Scull_dev *sculldev;

//………………………end of declerations………….
MODULE_AUTHOR(“Zaffer”);
MODULE_LICENSE(“GPL”);
//…………………………………………………..
55,1

LKO.C
int reg;
printk(KERN_INFO “Begin : %s\n”,__func__);
printk(KERN_INFO” HELLO KERNEL”);
printk(KERN_INFO “GREAT”);
if(scull_major)
{
dev=MKDEV(scull_major,scull_minor);
reg=register_chrdev_region(dev,scull_major,device_name);
}
else
{

reg=alloc_chrdev_region(&dev,scull_major,device_no,device_name);
scull_major=MAJOR(dev);
}
if(regcdev.owner=THIS_MODULE;
sculldev->cdev.ops=&fops;
cdev_init(&(sculldev->cdev),&fops );
int scull_open(struct inode *inode, struct file *filp)
{
// #ifdef DEBUG
// printk(KERN_INFO “open function performed sucessfully\n”);
— // #endif
return 0;
}
cdev_add(&(sculldev->cdev),dev,1);
return 0;
}
void __exit release(void)
{
#ifdef DEBUG
printk(KERN_INFO “exit : %s\n”,__func__);
#endif

printk(KERN_INFO “BYE KERNEL”);
unregister_chrdev_region(dev,device_no);
kfree(sculldev);
cdev_del(&(sculldev->cdev));

}

ISO C90 is a standard for the C programming language that specifies the rules and guidelines that C compilers should follow. One such rule is that mixed declarations and code are not allowed in C90. This means that all variable declarations must come before any executable statements in a block of code.

What are mixed declarations and code?

Mixed declarations and code refer to the practice of declaring variables and executing code in the same block. For example, consider the following code snippet:

int main() {
   int x = 2;
   printf("The value of x is %d", x);
   int y = 4;
   printf("The value of y is %d", y);
   return 0;
}

In this code, the variable `y` is declared after an executable statement (`printf`), which is not allowed in ISO C90.

How to fix mixed declarations and code?

To fix mixed declarations and code, all variable declarations must come before any executable statements in a block of code. Here is the corrected code:

int main() {
   int x = 2;
   int y = 4;
   printf("The value of x is %d", x);
   printf("The value of y is %d", y);
   return 0;
}

In this code, all variable declarations come before any executable statements, which is allowed in ISO C90.

Conclusion

ISO C90 forbids mixed declarations and code in C. This means that all variable declarations must come before any executable statements in a block of code. By following this rule, your code will be compliant with the ISO C90 standard.

Понравилась статья? Поделить с друзьями:
  • Ошибка isd dll
  • Ошибка isarcextract что делать
  • Ошибка is not valid integer value
  • Ошибка is not a valid win32 application
  • Ошибка irql not less or equal как исправить