Ошибка for loop initial declarations are only allowed in c99 mode

I am getting the below error, what is std=c99/std=gnu99 mode?

source Code:

#include <stdio.h>

void funct(int[5]);

int main() 
{        
    int Arr[5]={1,2,3,4,5};
    funct(Arr);
    for(int j=0;j<5;j++)
    printf("%d",Arr[j]);
}

void funct(int p[5]) {
        int i,j;
        for(i=6,j=0;i<11;i++,j++)
            p[j]=i;
}


Error Message:
hello.c: In function ‘main’:
hello.c:11:2: error: ‘for’ loop initial declarations are only allowed in C99 mode
for(int j=0;j<5;j++)
      ^
hello.c:11:2: note: use option -std=c99 or -std=gnu99 to compile your code`

Mathemats's user avatar

Mathemats

1,1854 gold badges22 silver badges35 bronze badges

asked Mar 30, 2015 at 4:02

Rajit s rajan's user avatar

1

This happens because declaring variables inside a for loop wasn’t valid C until C99(which is the standard of C published in 1999), you can either declare your counter outside the for as pointed out by others or use the -std=c99 flag to tell the compiler explicitly that you’re using this standard and it should interpret it as such.

user438383's user avatar

user438383

5,6078 gold badges28 silver badges41 bronze badges

answered Mar 30, 2015 at 4:11

Alex Díaz's user avatar

Alex DíazAlex Díaz

2,27315 silver badges24 bronze badges

2

You need to declare the variable j used for the first for loop before the loop.

    int j;
    for(j=0;j<5;j++)
    printf("%d",Arr[j]);

answered Mar 30, 2015 at 4:06

MySequel's user avatar

This will be working code

#include <stdio.h>

    void funct(int[5]);
    int main()
    {
         int Arr[5]={1,2,3,4,5};
         int j = 0;

        funct(Arr);

        for(j=0;j<5;j++)
        printf("%d",Arr[j]);
    }
    void funct(int p[5]){
        int i,j;
        for(i=6,j=0;i<11;i++,j++)
            p[j]=i;
    }

answered Mar 30, 2015 at 4:46

Yasir Majeed's user avatar

1

I am getting the below error, what is std=c99/std=gnu99 mode?

source Code:

#include <stdio.h>

void funct(int[5]);

int main() 
{        
    int Arr[5]={1,2,3,4,5};
    funct(Arr);
    for(int j=0;j<5;j++)
    printf("%d",Arr[j]);
}

void funct(int p[5]) {
        int i,j;
        for(i=6,j=0;i<11;i++,j++)
            p[j]=i;
}


Error Message:
hello.c: In function ‘main’:
hello.c:11:2: error: ‘for’ loop initial declarations are only allowed in C99 mode
for(int j=0;j<5;j++)
      ^
hello.c:11:2: note: use option -std=c99 or -std=gnu99 to compile your code`

Mathemats's user avatar

Mathemats

1,1854 gold badges22 silver badges35 bronze badges

asked Mar 30, 2015 at 4:02

Rajit s rajan's user avatar

1

This happens because declaring variables inside a for loop wasn’t valid C until C99(which is the standard of C published in 1999), you can either declare your counter outside the for as pointed out by others or use the -std=c99 flag to tell the compiler explicitly that you’re using this standard and it should interpret it as such.

user438383's user avatar

user438383

5,6078 gold badges28 silver badges41 bronze badges

answered Mar 30, 2015 at 4:11

Alex Díaz's user avatar

Alex DíazAlex Díaz

2,27315 silver badges24 bronze badges

2

You need to declare the variable j used for the first for loop before the loop.

    int j;
    for(j=0;j<5;j++)
    printf("%d",Arr[j]);

answered Mar 30, 2015 at 4:06

MySequel's user avatar

This will be working code

#include <stdio.h>

    void funct(int[5]);
    int main()
    {
         int Arr[5]={1,2,3,4,5};
         int j = 0;

        funct(Arr);

        for(j=0;j<5;j++)
        printf("%d",Arr[j]);
    }
    void funct(int p[5]){
        int i,j;
        for(i=6,j=0;i<11;i++,j++)
            p[j]=i;
    }

answered Mar 30, 2015 at 4:46

Yasir Majeed's user avatar

1

When I compile the following code it gives compilation error that

 error: ‘for’ loop initial declarations are only allowed in C99 mode
 for(int i = 0; i < 5; i++)

and to compile your code use this option :

 note: use option -std=c99 or -std=gnu99 to compile your code

Now my question is this how to use the above option and enable c99 and c11?

asked May 18, 2014 at 12:51

Mirwise Khan's user avatar

0

As conveyed in the error message, you should compile the code using -std=c99 or -std=gnu99. So, for example, your file is filename.c, then compile using:

gcc -std=c99 filename.c

which will produce a binary a.out if there are no more errors. If you don’t want to use this option, you can declare i before the for loop as follows:

int i;
for(i = 0; i < 5; i++)

and compile it using:

gcc filename.c

answered May 18, 2014 at 13:27

jobin's user avatar

jobinjobin

27k16 gold badges100 silver badges116 bronze badges

sotoges

0 / 0 / 0

Регистрация: 19.10.2017

Сообщений: 10

1

15.12.2017, 01:14. Показов 28381. Ответов 4

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Возникшие проблемы с кодом:

Кликните здесь для просмотра всего текста

main.c||In function ‘print’:|
main.c|5|error: ‘for’ loop initial declarations are only allowed in C99 mode|
main.c|5|note: use option -std=c99 or -std=gnu99 to compile your code|
main.c|7|error: ‘for’ loop initial declarations are only allowed in C99 mode|
main.c|17|error: redefinition of ‘i’|
main.c|5|note: previous definition of ‘i’ was here|
main.c|17|error: ‘for’ loop initial declarations are only allowed in C99 mode|
main.c||In function ‘clear’:|
main.c|23|error: ‘for’ loop initial declarations are only allowed in C99 mode|
main.c||In function ‘main’:|
main.c|42|error: ‘for’ loop initial declarations are only allowed in C99 mode|
||=== Build finished: 6 errors, 0 warnings (0 minutes, 0 seconds) ===|

Код:

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <string.h>
void print(char word[], int length)
{
for(int i = 0; i < length; i++)
{
for(int k = length-1; k > i; k--)
{
if(word[k-1] > word[k])
{
char temp = word[k];
word[k] = word[k-1];
word[k-1] = temp;
}
}
}
for(int i = 0; i < length; i++)
printf("%c", word[i]);
}
void clear(char word[])
{
int size = strlen(word);
for(int i = 0; i <= size; i++)
{
word[i] = '';
}
}
int main ()
{
char text [1024], word[20];
puts("Введите текст");
scanf("%s", text);
int end = strlen(text);
int end_index = 0;
int index = 0;
int length = 1;
do
{
clear(word);
int k = 0;
end_index = index + length;
for(int i = index; i < end_index; i++)
{
word[k] = text[i];
k++;
}
index = end_index;
print(word, length);
printf("n");
length++;
} while((end_index + length) <= end);
return 0;
}



0



sotoges

0 / 0 / 0

Регистрация: 19.10.2017

Сообщений: 10

15.12.2017, 01:32

 [ТС]

2

Возникшие проблемы с кодом:

Кликните здесь для просмотра всего текста

main.c||In function ‘main’:|
main.c|9|error: unknown type name ‘foat’|
main.c|19|error: ‘for’ loop initial declarations are only allowed in C99 mode|
main.c|19|note: use option -std=c99 or -std=gnu99 to compile your code|
main.c|23|warning: format ‘%f’ expects argument of type ‘float *’, but argument 3 has type ‘int *’ [-Wformat]|
main.c|28|error: redefinition of ‘i’|
main.c|19|note: previous definition of ‘i’ was here|
main.c|28|error: ‘for’ loop initial declarations are only allowed in C99 mode|
main.c|33|warning: format ‘%f’ expects argument of type ‘double’, but argument 3 has type ‘int’ [-Wformat]|
main.c|38|error: redefinition of ‘i’|
main.c|28|note: previous definition of ‘i’ was here|
main.c|38|error: ‘for’ loop initial declarations are only allowed in C99 mode|
main.c|46|error: unknown type name ‘foat’|
main.c|47|warning: format ‘%f’ expects argument of type ‘float *’, but argument 2 has type ‘int *’ [-Wformat]|
main.c|48|error: redefinition of ‘i’|
main.c|38|note: previous definition of ‘i’ was here|
main.c|48|error: ‘for’ loop initial declarations are only allowed in C99 mode|
main.c|51|warning: format ‘%f’ expects argument of type ‘double’, but argument 3 has type ‘int’ [-Wformat]|
main.c|53|error: redefinition of ‘i’|
main.c|48|note: previous definition of ‘i’ was here|
main.c|53|error: ‘for’ loop initial declarations are only allowed in C99 mode|
main.c|56|error: ‘for’ loop initial declarations are only allowed in C99 mode|
||=== Build finished: 12 errors, 4 warnings (0 minutes, 0 seconds) ===|

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <stdio.h>
#include <string.h>
#include <locale.h>
int main()
{
struct toy
{
char name[1024];
foat price;
int lower_limit;
int upper_limit;
};
int amount;
setlocale(LC_ALL,"RUS");
puts("Введите количество игрушек");
scanf("%d", &amount);
 
struct toy toys[amount];
for(int i = 0; i < amount; i++)
{
printf("Введите название, цену и возрастной диапазон для %d игрушкиn", i+1);
scanf("%s%f%d%d", toys[i].name, &toys[i].price,
&toys[i].lower_limit, &toys[i].upper_limit);
}
puts("Ввод информации завершён");
//Поиск самое дорогой игрушки
int max_price = 0;;
for(register int i = 0; i < amount; i++)
{
if (toys[max_price].price < toys[i].price)
max_price = i;
}
printf("Самая дорогоая игрушка - %s стоимостью %.2fn",toys[max_price]. name, toys[max_price].price);
//Подбор игрушек по возрасту
puts("Введите возраст Вашего ребёнка");
int age;
scanf("%d", &age);
for (register int i = 0; i < amount; i++)
{
if ((toys[i].lower_limit < age) && (age < toys[i].upper_limit))
{
printf("Вашему ребёнку подойдёт %sn", toys[i].name);
}
}
puts("Введите ваш бюджет");
foat budget, total_price = 0;
scanf("%f", &budget);
for (register int i = 0; i < amount; i++)
{
if (toys[i].price <= budget)
printf("Вы можете купить %s на ваши деньги. У вас как раз останется %.2f на чашечку кофеn", toys[i].name, budget - toys[i].price);
}
for (register int i = 0; i < amount; i++)
{
total_price = toys[i].price;
for (register int k = 0; k < amount; k++)
{
total_price += toys[k].price;
if (total_price <= budget)
{
printf("Вы можете купить на ваши деньги комплект из %s и %sn", toys[i].name, toys[k].name);
}
}
}
return 0;
}



0



3595 / 2267 / 407

Регистрация: 09.09.2017

Сообщений: 9,524

15.12.2017, 08:48

3

Цитата
Сообщение от sotoges
Посмотреть сообщение

main.c|9|error: unknown type name ‘foat’|

Возможно, имелся в виду float?

Цитата
Сообщение от sotoges
Посмотреть сообщение

main.c|19|error: ‘for’ loop initial declarations are only allowed in C99 mode|

Либо включите совместимость с С99 или выше (в gcc это -std=c99), собственно, в следующей строке вам это и написали, либо вынесите объявление переменной в начало функции.
Большая часть остальных сообщений — следствие этих двух ошибок



0



14 / 14 / 0

Регистрация: 01.12.2017

Сообщений: 577

15.12.2017, 12:51

4

int i объяви в начале функции. а в for (i=0;i<=size; i++)



0



LaFayette

48 / 48 / 57

Регистрация: 25.11.2015

Сообщений: 140

15.12.2017, 13:11

5

Цитата
Сообщение от sotoges
Посмотреть сообщение

main.c||In function ‘print’:|
main.c|5|error: ‘for’ loop initial declarations are only allowed in C99 mode|
main.c|5|note: use option -std=c99 or -std=gnu99 to compile your code|

Инициализация в цикле for доступна начиная со стандарта С99. Для использования стандарта во время компиляции нужно добавить опцию -std=c99.

Например

Bash
1
gcc hello.c -std=c99 -o hello.exe



0



Describe the bug

The default compiler on RHEL7 (also Centos7) is gcc 4.8.x, which requires specifying the -std=c99 flag.

Full error log

nvim-treesitter[vim]: Error during compilation
src/scanner.c: In function ‘check_prefix’:
src/scanner.c:221:3: error: ‘for’ loop initial declarations are only allowed in C99 mode
   for (unsigned int i = 0; i < preffix_len; i++) {
   ^
src/scanner.c:221:3: note: use option -std=c99 or -std=gnu99 to compile your code
src/scanner.c: In function ‘try_lex_script_start’:
src/scanner.c:243:3: error: ‘for’ loop initial declarations are only allowed in C99 mode
   for(size_t j = 0; j < 2; j++) {
   ^
src/scanner.c: In function ‘try_lex_keyword’:
src/scanner.c:367:15: error: redeclaration of ‘i’ with no linkage
   for (size_t i = 0; keyword.opt[i] && possible[mandat_len + i]; i++) {
               ^
src/scanner.c:358:10: note: previous declaration of ‘i’ was here
   size_t i;
          ^
src/scanner.c:367:3: error: ‘for’ loop initial declarations are only allowed in C99 mode
   for (size_t i = 0; keyword.opt[i] && possible[mandat_len + i]; i++) {
   ^
src/scanner.c: In function ‘scope_correct’:
src/scanner.c:378:3: error: ‘for’ loop initial declarations are only allowed in C99 mode
   for (size_t i = 0; SCOPES[i]; i++) {
   ^
src/scanner.c: In function ‘lex_scope’:
src/scanner.c:395:5: error: ‘for’ loop initial declarations are only allowed in C99 mode
     for (size_t i = 0; sid[i] && lexer->lookahead; i++) {
     ^
src/scanner.c: In function ‘tree_sitter_vim_external_scanner_scan’:
src/scanner.c:518:5: error: ‘for’ loop initial declarations are only allowed in C99 mode
     for (size_t i = 0; i < s->marker_len; i++) {
     ^
src/scanner.c:575:5: error: ‘for’ loop initial declarations are only allowed in C99 mode
     for (enum TokenType t = TRIE_START; t < TOKENTYPE_NR; t++) {
     ^

To Reproduce

:TSInstall vim

minimal_init.lua

local on_windows = vim.loop.os_uname().version:match("Windows")

local function join_paths(...)
	local path_sep = on_windows and "\" or "/"
	local result = table.concat({ ... }, path_sep)
	return result
end

vim.cmd([[set runtimepath=$VIMRUNTIME]])

local temp_dir = vim.loop.os_getenv("TEMP") or "/tmp"

vim.cmd("set packpath=" .. join_paths(temp_dir, "nvim", "site"))

local package_root = join_paths(temp_dir, "nvim", "site", "pack")
local install_path = join_paths(package_root, "packer", "start", "packer.nvim")
local compile_path = join_paths(install_path, "plugin", "packer_compiled.lua")

local function load_plugins()
	require("packer").startup({
		{
			"wbthomason/packer.nvim",
			{
				"nvim-treesitter/nvim-treesitter",
				branch = vim.fn.has("nvim-0.6") == 1 and "master" or "0.5-compat",
			},
		},
		config = {
			package_root = package_root,
			compile_path = compile_path,
		},
	})
end

_G.load_config = function()
	local status_ok, treesitter_configs = pcall(require, "nvim-treesitter.configs")
	if not status_ok then
		error("unable to load treesitter")
		return
	end

	local opts = {}

	treesitter_configs.setup(opts)
end

if vim.fn.isdirectory(install_path) == 0 then
	vim.fn.system({ "git", "clone", "https://github.com/wbthomason/packer.nvim", install_path })
	load_plugins()
	require("packer").sync()
	vim.cmd([[autocmd User PackerComplete ++once lua load_config()]])
else
	load_plugins()
	require("packer").sync()
	_G.load_config()
end

Expected behavior

NA

Output of :checkhealth nvim-treesitter

nvim-treesitter: require("nvim-treesitter.health").check()
========================================================================
## Installation
  - WARNING: `tree-sitter` executable not found (parser generator, only needed for :TSInstallFromGrammar, not required for :    TSInstall)
  - OK: `node` found v15.14.0 (only needed for :TSInstallFromGrammar)
  - OK: `git` executable found.
  - OK: `cc` executable found. Selected from { vim.NIL, "cc", "gcc", "clang", "cl", "zig" }
    Version: cc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)
  - OK: Neovim was compiled with tree-sitter runtime ABI version 13 (required >=13). Parsers must be compatible with runtime    ABI.

## Parser/Features H L F I J

  Legend: H[ighlight], L[ocals], F[olds], I[ndents], In[j]ections
         +) multiple parsers found, only one will be used
         x) errors found in the query, try to run :TSUpdate {lang}

Output of nvim --version

NVIM v0.7.0-dev+948-gc5ac04331
Build type: Release
LuaJIT 2.1.0-beta3
...

Additional context

No response

  • Ошибка for honor appdata folder detection error
  • Ошибка for atheros pcie ethernet controller v2
  • Ошибка font элемент устарел вместо этого используйте css
  • Ошибка folder is not accessible
  • Ошибка folder invalid при установке мода гта сан андреас