threads / patch / 60925

patchuse C99 declaration of variable in for() loop

Subject: [PATCH] use C99 declaration of variable in for() loop

## tl;dr

8 messages between Feb 15, 2024 and Feb 15, 2024. Diffs are folded; open one to read it.

replies: 7people: 4as markdown or json

Elia Pinto· Feb 15, 2024, 09:42 UTC · lore

With the exception of cbtree.c, which would need initial reworking to remove the usage of goto, it expands the use of variable scope reduction in for loops as permitted by the C99 standard, which was first introduced in the git codebase with commit 44ba10d6.

Signed-off-by: Elia Pinto <gitter.spiros@gmail.com>
---
Based on top of next 049e64211f79bdc0639badd06a79810dd7b3b85c
 add-interactive.c                    | 29 ++++-----
 add-patch.c                          | 16 +++--
 advice.c                             | 11 ++--
 apply.c                              | 39 +++++-------
 archive-tar.c                        | 10 ++-
 archive.c                            | 11 +---
 attr.c                               | 24 +++----
 base85.c                             |  3 +-
 bisect.c                             | 23 +++----
 blame.c                              | 92 ++++++++++-----------------
 bloom.c                              | 17 ++---
 branch.c                             |  3 +-
 builtin/add.c                        | 15 +++--
 builtin/am.c                         |  3 +-
 builtin/annotate.c                   |  3 +-
 builtin/archive.c                    |  4 +-
 builtin/bisect.c                     |  7 +--
 builtin/blame.c                      | 14 ++---
 builtin/branch.c                     | 15 ++---
 builtin/bugreport.c                  |  4 +-
 builtin/cat-file.c                   |  8 +--
 builtin/check-attr.c                 |  3 +-
 builtin/check-ignore.c               |  4 +-
 builtin/check-mailmap.c              |  3 +-
 builtin/checkout--worker.c           |  4 +-
 builtin/checkout-index.c             |  7 +--
 builtin/checkout.c                   |  6 +-
 builtin/clean.c                      | 17 +++--
 builtin/clone.c                      | 17 ++---
 builtin/commit-tree.c                |  3 +-
 builtin/commit.c                     | 11 ++--
 builtin/config.c                     |  3 +-
 builtin/count-objects.c              |  3 +-
 builtin/credential-cache--daemon.c   |  8 +--
 builtin/describe.c                   |  4 +-
 builtin/diff-index.c                 |  3 +-
 builtin/diff.c                       |  7 +--
 builtin/fast-export.c                | 24 +++----
 builtin/fast-import.c                | 56 +++++++----------
 builtin/fetch-pack.c                 |  4 +-
 builtin/fetch.c                      | 39 ++++--------
 builtin/for-each-repo.c              |  7 +--
 builtin/fsck.c                       | 22 +++----
 builtin/fsmonitor--daemon.c          | 14 +----
 builtin/gc.c                         | 28 +++------
 builtin/grep.c                       | 24 +++----
 builtin/hash-object.c                |  3 +-
 builtin/help.c                       | 14 ++---
 builtin/hook.c                       |  3 +-
 builtin/index-pack.c                 | 13 ++--
 builtin/interpret-trailers.c         |  3 +-
 builtin/log.c                        | 17 ++---
 builtin/ls-files.c                   | 14 ++---
 builtin/ls-tree.c                    |  8 +--
 builtin/mailsplit.c                  |  6 +-
 builtin/merge-base.c                 | 20 +++---
 builtin/merge-index.c                |  3 +-
 builtin/merge-tree.c                 |  9 +--
 builtin/merge.c                      | 36 +++++------
 builtin/name-rev.c                   | 11 ++--
 builtin/notes.c                      |  4 +-
 builtin/pack-objects.c               | 49 +++++----------
 builtin/pack-redundant.c             |  3 +-
 builtin/pull.c                       |  6 +-
 builtin/push.c                       |  4 +-
 builtin/range-diff.c                 |  4 +-
 builtin/read-tree.c                  |  4 +-
 builtin/receive-pack.c               | 46 +++++---------
 builtin/reflog.c                     | 16 +++--
 builtin/remote.c                     | 37 +++++------
 builtin/repack.c                     | 24 +++----
 builtin/replace.c                    | 10 ++-
 builtin/replay.c                     |  4 +-
 builtin/rerere.c                     |  3 +-
 builtin/reset.c                      |  7 +--
 builtin/rev-list.c                   |  3 +-
 builtin/rm.c                         | 10 ++-
 builtin/send-pack.c                  |  3 +-
 builtin/shortlog.c                   |  4 +-
 builtin/show-branch.c                |  4 +-
 builtin/sparse-checkout.c            | 11 ++--
 builtin/stash.c                      | 27 +++-----
 builtin/submodule--helper.c          | 40 +++++-------
 builtin/tag.c                        |  3 +-
 builtin/unpack-objects.c             |  9 +--
 builtin/update-index.c               |  9 +--
 builtin/var.c                        |  6 +-
 builtin/verify-pack.c                |  3 +-
 builtin/worktree.c                   | 12 ++--
 bulk-checkin.c                       |  7 +--
 bundle-uri.c                         |  6 +-
 bundle.c                             | 21 +++----
 cache-tree.c                         | 21 +++----
 chunk-format.c                       |  4 +-
 color.c                              |  9 +--
 column.c                             | 22 +++----
 combine-diff.c                       | 18 +++---
 commit-graph.c                       | 52 ++++++----------
 commit-reach.c                       | 26 +++-----
 commit.c                             | 23 +++----
 compat/fsmonitor/fsm-health-win32.c  |  4 +-
 compat/fsmonitor/fsm-listen-darwin.c |  8 +--
 compat/mingw.c                       |  6 +-
 compat/simple-ipc/ipc-unix-socket.c  | 11 +---
 compat/simple-ipc/ipc-win32.c        |  3 +-
 compat/strcasestr.c                  |  7 +--
 compat/terminal.c                    |  7 +--
 compat/unsetenv.c                    |  4 +-
 config.c                             | 15 ++---
 connect.c                            | 15 ++---
 connected.c                          |  4 +-
 convert.c                            | 18 ++----
 credential.c                         | 12 +---
 daemon.c                             | 21 +++----
 date.c                               |  3 +-
 decorate.c                           |  6 +-
 delta-islands.c                      | 27 +++-----
 diagnose.c                           |  3 +-
 diff-delta.c                         |  6 +-
 diff-lib.c                           |  4 +-
 diff.c                               | 93 ++++++++++------------------
 diff.h                               |  4 +-
 diffcore-break.c                     |  7 +--
 diffcore-delta.c                     |  3 +-
 diffcore-order.c                     | 11 ++--
 diffcore-rename.c                    | 17 +++--
 dir.c                                | 57 +++++++----------
 entry.c                              |  4 +-
 environment.c                        |  4 +-
 ewah/bitmap.c                        | 21 +++----
 ewah/ewah_io.c                       |  3 +-
 fetch-pack.c                         | 40 ++++--------
 fmt-merge-msg.c                      | 14 ++---
 fsck.c                               | 19 ++----
 fsmonitor.c                          |  9 ++-
 git.c                                | 16 ++---
 gpg-interface.c                      | 20 +++---
 graph.c                              | 51 +++++----------
 grep.c                               | 21 +++----
 hash-lookup.c                        |  4 +-
 hashmap.c                            |  4 +-
 help.c                               | 34 ++++------
 hex.c                                |  9 +--
 http-backend.c                       | 10 ++-
 http-push.c                          | 10 +--
 http-walker.c                        |  3 +-
 http.c                               | 13 ++--
 ident.c                              | 12 +---
 imap-send.c                          |  4 +-
 json-writer.c                        | 15 ++---
 khash.h                              |  8 +--
 line-log.c                           | 43 +++++--------
 linear-assignment.c                  |  4 +-
 list-objects-filter-options.c        | 11 +---
 list-objects-filter.c                | 14 ++---
 list-objects.c                       | 17 ++---
 log-tree.c                           | 10 ++-
 ls-refs.c                            |  4 +-
 mailinfo.c                           | 25 +++-----
 mem-pool.c                           |  5 +-
 merge-ll.c                           | 10 ++-
 merge-ort.c                          | 62 +++++++------------
 merge-recursive.c                    | 27 +++-----
 merge.c                              |  8 +--
 midx.c                               | 62 ++++++-------------
 name-hash.c                          | 19 ++----
 negotiator/skipping.c                |  3 +-
 notes-merge.c                        | 11 ++--
 notes-utils.c                        |  6 +-
 notes.c                              | 30 +++------
 object-file.c                        | 40 ++++--------
 object-name.c                        | 55 +++++-----------
 object.c                             | 42 ++++---------
 oid-array.c                          | 14 ++---
 pack-bitmap-write.c                  | 25 +++-----
 pack-bitmap.c                        | 51 ++++++---------
 pack-objects.c                       | 12 ++--
 pack-revindex.c                      |  8 +--
 pack-write.c                         | 13 ++--
 packfile.c                           | 82 ++++++++----------------
 pager.c                              |  3 +-
 parallel-checkout.c                  |  7 +--
 parse-options.c                      |  8 +--
 path.c                               | 11 ++--
 pathspec.c                           | 26 ++++----
 pkt-line.c                           |  3 +-
 pretty.c                             | 25 +++-----
 prio-queue.c                         | 12 ++--
 promisor-remote.c                    |  6 +-
 quote.c                              | 11 +---
 reachable.c                          |  3 +-
 read-cache.c                         | 62 ++++++-------------
 ref-filter.c                         | 50 +++++----------
 reflog-walk.c                        | 15 ++---
 refs.c                               | 58 ++++++-----------
 refs/debug.c                         |  3 +-
 refs/files-backend.c                 | 15 ++---
 refs/packed-backend.c                |  9 +--
 refs/ref-cache.c                     | 16 +----
 refs/reftable-backend.c              |  7 +--
 refspec.c                            |  6 +-
 reftable/basics.c                    |  3 +-
 reftable/block.c                     |  3 +-
 reftable/merged_test.c               |  3 +-
 reftable/pq_test.c                   |  3 +-
 reftable/readwrite_test.c            | 16 ++---
 reftable/record.c                    |  4 +-
 reftable/record_test.c               |  4 +-
 reftable/refname_test.c              |  3 +-
 reftable/stack.c                     | 12 ++--
 reftable/stack_test.c                | 28 ++++-----
 remote-curl.c                        |  6 +-
 remote.c                             | 84 +++++++++----------------
 rerere.c                             | 17 ++---
 revision.c                           | 69 +++++++--------------
 run-command.c                        | 21 ++-----
 scalar.c                             |  7 +--
 send-pack.c                          | 10 ++-
 sequencer.c                          | 40 +++++-------
 serve.c                              |  7 +--
 server-info.c                        | 12 ++--
 setup.c                              | 11 +---
 shallow.c                            | 13 ++--
 shell.c                              |  3 +-
 sideband.c                           | 11 +---
 sparse-index.c                       | 10 +--
 split-index.c                        | 16 +----
 strbuf.c                             | 20 +++---
 string-list.c                        | 12 ++--
 strvec.c                             |  3 +-
 submodule.c                          | 28 +++------
 t/helper/test-bloom.c                |  7 +--
 t/helper/test-dump-cache-tree.c      |  3 +-
 t/helper/test-dump-fsmonitor.c       |  3 +-
 t/helper/test-dump-split-index.c     |  3 +-
 t/helper/test-example-decorate.c     |  4 +-
 t/helper/test-fake-ssh.c             |  3 +-
 t/helper/test-find-pack.c            |  3 +-
 t/helper/test-fsmonitor-client.c     |  3 +-
 t/helper/test-lazy-init-name-hash.c  |  4 +-
 t/helper/test-mergesort.c            | 25 +++-----
 t/helper/test-pack-mtimes.c          |  3 +-
 t/helper/test-parse-options.c        |  3 +-
 t/helper/test-parse-pathspec-file.c  |  4 +-
 t/helper/test-path-utils.c           | 12 ++--
 t/helper/test-pkt-line.c             |  3 +-
 t/helper/test-proc-receive.c         |  4 +-
 t/helper/test-reach.c                | 10 ++-
 t/helper/test-read-cache.c           |  4 +-
 t/helper/test-read-midx.c            |  3 +-
 t/helper/test-ref-store.c            |  3 +-
 t/helper/test-repository.c           |  3 +-
 t/helper/test-rot13-filter.c         | 10 ++-
 t/helper/test-run-command.c          |  4 +-
 t/helper/test-simple-ipc.c           | 18 ++----
 t/helper/test-string-list.c          |  3 +-
 t/helper/test-submodule.c            |  3 +-
 t/helper/test-tool.c                 |  7 +--
 t/helper/test-trace2.c               | 16 ++---
 t/helper/test-wildmatch.c            |  3 +-
 t/helper/test-write-cache.c          |  4 +-
 t/unit-tests/test-lib.c              |  4 +-
 tmp-objdir.c                         |  3 +-
 trace2/tr2_cfg.c                     |  6 +-
 trace2/tr2_ctr.c                     | 15 +----
 trace2/tr2_sid.c                     |  3 +-
 trace2/tr2_sysenv.c                  |  8 +--
 trace2/tr2_tmr.c                     | 15 +----
 trailer.c                            | 28 +++------
 transport-helper.c                   | 31 ++++------
 transport.c                          | 29 +++------
 tree-diff.c                          |  3 +-
 tree-walk.c                          | 11 ++--
 unpack-trees.c                       | 48 +++++---------
 upload-pack.c                        | 33 +++-------
 userdiff.c                           |  3 +-
 version.c                            |  3 +-
 versioncmp.c                         |  6 +-
 walker.c                             |  4 +-
 worktree.c                           |  8 +--
 wrapper.c                            |  4 +-
 ws.c                                 |  3 +-
 wt-status.c                          | 51 ++++++---------
 xdiff-interface.c                    |  6 +-
 xdiff/xdiffi.c                       | 19 ++----
 xdiff/xemit.c                        |  8 +--
 xdiff/xhistogram.c                   |  4 +-
 xdiff/xmerge.c                       |  3 +-
 xdiff/xpatience.c                    |  3 +-
 289 files changed, 1452 insertions(+), 2766 deletions(-)
Show changes to 93 files +441 −800

add-interactive.c, add-patch.c, advice.c, apply.c, archive-tar.c, archive.c, attr.c, base85.c, bisect.c, blame.c, bloom.c, branch.c, builtin/add.c, builtin/am.c, builtin/annotate.c, builtin/archive.c, builtin/bisect.c, builtin/blame.c, builtin/branch.c, builtin/bugreport.c, builtin/cat-file.c, builtin/check-attr.c, builtin/check-ignore.c, builtin/check-mailmap.c, builtin/checkout--worker.c, builtin/checkout-index.c, builtin/checkout.c, builtin/clean.c, builtin/clone.c, builtin/commit-tree.c, builtin/commit.c, builtin/config.c, builtin/count-objects.c, builtin/credential-cache--daemon.c, builtin/describe.c, builtin/diff-index.c, builtin/diff.c, builtin/fast-export.c, builtin/fast-import.c, builtin/fetch-pack.c, builtin/fetch.c, builtin/for-each-repo.c, builtin/fsck.c, builtin/fsmonitor--daemon.c, builtin/gc.c, builtin/grep.c, builtin/hash-object.c, builtin/help.c, builtin/hook.c, builtin/index-pack.c, builtin/interpret-trailers.c, builtin/log.c, builtin/ls-files.c, builtin/ls-tree.c, builtin/mailsplit.c, builtin/merge-base.c, builtin/merge-index.c, builtin/merge-tree.c, builtin/merge.c, builtin/name-rev.c, builtin/notes.c, builtin/pack-objects.c, builtin/pack-redundant.c, builtin/pull.c, builtin/push.c, builtin/range-diff.c, builtin/read-tree.c, builtin/receive-pack.c, builtin/reflog.c, builtin/remote.c, builtin/repack.c, builtin/replace.c, builtin/replay.c, builtin/rerere.c, builtin/reset.c, builtin/rev-list.c, builtin/rm.c, builtin/send-pack.c, builtin/shortlog.c, builtin/show-branch.c, builtin/sparse-checkout.c, builtin/stash.c, builtin/submodule--helper.c, builtin/tag.c, builtin/unpack-objects.c, builtin/update-index.c, builtin/var.c, builtin/verify-pack.c, builtin/worktree.c, bulk-checkin.c, bundle-uri.c, bundle.c, cache-tree.c

diff --git a/add-interactive.c b/add-interactive.c
index 6bf87e7ae7..58ad10be10 100644
--- a/add-interactive.c
+++ b/add-interactive.c
@@ -233,7 +233,7 @@ struct list_options {
 static void list(struct add_i_state *s, struct string_list *list, int *selected,
 		 struct list_options *opts)
 {
-	int i, last_lf = 0;
+	int last_lf = 0;
 
 	if (!list->nr)
 		return;
@@ -242,7 +242,7 @@ static void list(struct add_i_state *s, struct string_list *list, int *selected,
 		color_fprintf_ln(stdout, s->header_color,
 				 "%s", opts->header);
 
-	for (i = 0; i < list->nr; i++) {
+	for (int i = 0; i < list->nr; i++) {
 		opts->print_item(i, selected ? selected[i] : 0, list->items + i,
 				 opts->print_item_data);
 
@@ -467,14 +467,13 @@ static void collect_changes_cb(struct diff_queue_struct *q,
 {
 	struct collection_status *s = data;
 	struct diffstat_t stat = { 0 };
-	int i;
 
 	if (!q->nr)
 		return;
 
 	compute_diffstat(options, &stat, q);
 
-	for (i = 0; i < stat.nr; i++) {
+	for (int i = 0; i < stat.nr; i++) {
 		const char *name = stat.files[i]->name;
 		int hash = strhash(name);
 		struct pathname_entry *entry;
@@ -535,7 +534,6 @@ static int get_modified_files(struct repository *r,
 	int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING,
 					     &head_oid, NULL);
 	struct collection_status s = { 0 };
-	int i;
 
 	discard_index(r->index);
 	if (repo_read_index_preload(r, ps, 0) < 0)
@@ -545,7 +543,7 @@ static int get_modified_files(struct repository *r,
 	s.files = &files->items;
 	hashmap_init(&s.file_map, pathname_entry_cmp, NULL, 0);
 
-	for (i = 0; i < 2; i++) {
+	for (int i = 0; i < 2; i++) {
 		struct rev_info rev;
 		struct setup_revision_opt opt = { 0 };
 
@@ -678,7 +676,7 @@ static int run_update(struct add_i_state *s, const struct pathspec *ps,
 		      struct list_and_choose_options *opts)
 {
 	int res = 0, fd;
-	size_t count, i;
+	size_t count;
 	struct lock_file index_lock;
 
 	if (get_modified_files(s->r, WORKTREE_ONLY, files, ps, NULL, NULL) < 0)
@@ -702,7 +700,7 @@ static int run_update(struct add_i_state *s, const struct pathspec *ps,
 		return -1;
 	}
 
-	for (i = 0; i < files->items.nr; i++) {
+	for (size_t i = 0; i < files->items.nr; i++) {
 		const char *name = files->items.items[i].string;
 		struct stat st;
 
@@ -733,9 +731,9 @@ static int run_update(struct add_i_state *s, const struct pathspec *ps,
 static void revert_from_diff(struct diff_queue_struct *q,
 			     struct diff_options *opt, void *data UNUSED)
 {
-	int i, add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
+	int add_flags = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE;
 
-	for (i = 0; i < q->nr; i++) {
+	for (int i = 0; i < q->nr; i++) {
 		struct diff_filespec *one = q->queue[i]->one;
 		struct cache_entry *ce;
 
@@ -758,7 +756,7 @@ static int run_revert(struct add_i_state *s, const struct pathspec *ps,
 		      struct list_and_choose_options *opts)
 {
 	int res = 0, fd;
-	size_t count, i, j;
+	size_t count, j;
 
 	struct object_id oid;
 	int is_initial = !resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &oid,
@@ -799,7 +797,7 @@ static int run_revert(struct add_i_state *s, const struct pathspec *ps,
 	}
 
 	ALLOC_ARRAY(paths, count + 1);
-	for (i = j = 0; i < files->items.nr; i++)
+	for (size_t i = j = 0; i < files->items.nr; i++)
 		if (files->selected[i])
 			paths[j++] = files->items.items[i].string;
 	paths[j] = NULL;
@@ -843,7 +841,6 @@ static int get_untracked_files(struct repository *r,
 			       const struct pathspec *ps)
 {
 	struct dir_struct dir = { 0 };
-	size_t i;
 	struct strbuf buf = STRBUF_INIT;
 
 	if (repo_read_index(r) < 0)
@@ -854,7 +851,7 @@ static int get_untracked_files(struct repository *r,
 	add_pattern_list(&dir, EXC_CMDL, "--exclude option");
 	fill_directory(&dir, r->index, ps);
 
-	for (i = 0; i < dir.nr; i++) {
+	for (size_t i = 0; i < dir.nr; i++) {
 		struct dir_entry *ent = dir.entries[i];
 
 		if (index_name_is_other(r->index, ent->name, ent->len)) {
@@ -874,7 +871,7 @@ static int run_add_untracked(struct add_i_state *s, const struct pathspec *ps,
 {
 	struct print_file_item_data *d = opts->list_opts.print_item_data;
 	int res = 0, fd;
-	size_t count, i;
+	size_t count;
 	struct lock_file index_lock;
 
 	if (get_untracked_files(s->r, files, ps) < 0)
@@ -898,7 +895,7 @@ static int run_add_untracked(struct add_i_state *s, const struct pathspec *ps,
 		goto finish_add_untracked;
 	}
 
-	for (i = 0; i < files->items.nr; i++) {
+	for (size_t i = 0; i < files->items.nr; i++) {
 		const char *name = files->items.items[i].string;
 		if (files->selected[i] &&
 		    add_file_to_index(s->r->index, name, 0) < 0) {
diff --git a/add-patch.c b/add-patch.c
index 68f525b35c..219bcc9c9d 100644
--- a/add-patch.c
+++ b/add-patch.c
@@ -275,13 +275,11 @@ struct add_p_state {
 
 static void add_p_state_clear(struct add_p_state *s)
 {
-	size_t i;
-
 	strbuf_release(&s->answer);
 	strbuf_release(&s->buf);
 	strbuf_release(&s->plain);
 	strbuf_release(&s->colored);
-	for (i = 0; i < s->file_diff_nr; i++)
+	for (size_t i = 0; i < s->file_diff_nr; i++)
 		free(s->file_diff[i].hunk);
 	free(s->file_diff);
 	clear_add_i_state(&s->s);
@@ -407,7 +405,7 @@ static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
 	struct strbuf *plain = &s->plain, *colored = NULL;
 	struct child_process cp = CHILD_PROCESS_INIT;
 	char *p, *pend, *colored_p = NULL, *colored_pend = NULL, marker = '\0';
-	size_t file_diff_alloc = 0, i, color_arg_index;
+	size_t file_diff_alloc = 0, color_arg_index;
 	struct file_diff *file_diff = NULL;
 	struct hunk *hunk = NULL;
 	int res;
@@ -427,7 +425,7 @@ static int parse_diff(struct add_p_state *s, const struct pathspec *ps)
 	/* Use `--no-color` explicitly, just in case `diff.color = always`. */
 	strvec_pushl(&args, "--no-color", "--ignore-submodules=dirty", "-p",
 		     "--", NULL);
-	for (i = 0; i < ps->nr; i++)
+	for (size_t i = 0; i < ps->nr; i++)
 		strvec_push(&args, ps->items[i].original);
 
 	setup_child_process(s, &cp, NULL);
@@ -878,12 +876,12 @@ static void reassemble_patch(struct add_p_state *s,
 			     struct strbuf *out)
 {
 	struct hunk *hunk;
-	size_t save_len = s->plain.len, i;
+	size_t save_len = s->plain.len;
 	ssize_t delta = 0;
 
 	render_diff_header(s, file_diff, 0, out);
 
-	for (i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
+	for (size_t i = file_diff->mode_change; i < file_diff->hunk_nr; i++) {
 		struct hunk merged = { 0 };
 
 		hunk = file_diff->hunk + i;
@@ -1722,7 +1720,7 @@ int run_add_p(struct repository *r, enum add_p_mode mode,
 	struct add_p_state s = {
 		{ r }, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT, STRBUF_INIT
 	};
-	size_t i, binary_count = 0;
+	size_t binary_count = 0;
 
 	init_add_i_state(&s.s, r);
 
@@ -1761,7 +1759,7 @@ int run_add_p(struct repository *r, enum add_p_mode mode,
 		return -1;
 	}
 
-	for (i = 0; i < s.file_diff_nr; i++)
+	for (size_t i = 0; i < s.file_diff_nr; i++)
 		if (s.file_diff[i].binary && !s.file_diff[i].hunk_nr)
 			binary_count++;
 		else if (patch_update_file(&s, s.file_diff + i))
diff --git a/advice.c b/advice.c
index 6e9098ff08..e1606a0afd 100644
--- a/advice.c
+++ b/advice.c
@@ -93,14 +93,14 @@ static void vadvise(const char *advice, int display_instructions,
 		    const char *key, va_list params)
 {
 	struct strbuf buf = STRBUF_INIT;
-	const char *cp, *np;
+	const char *np;
 
 	strbuf_vaddf(&buf, advice, params);
 
 	if (display_instructions)
 		strbuf_addf(&buf, turn_off_instructions, key);
 
-	for (cp = buf.buf; *cp; cp = np) {
+	for (const char *cp = buf.buf; *cp; cp = np) {
 		np = strchrnul(cp, '\n');
 		fprintf(stderr,	_("%shint: %.*s%s\n"),
 			advise_get_color(ADVICE_COLOR_HINT),
@@ -147,7 +147,6 @@ void advise_if_enabled(enum advice_type type, const char *advice, ...)
 int git_default_advice_config(const char *var, const char *value)
 {
 	const char *k, *slot_name;
-	int i;
 
 	if (!strcmp(var, "color.advice")) {
 		advice_use_color = git_config_colorbool(var, value);
@@ -166,7 +165,7 @@ int git_default_advice_config(const char *var, const char *value)
 	if (!skip_prefix(var, "advice.", &k))
 		return 0;
 
-	for (i = 0; i < ARRAY_SIZE(advice_setting); i++) {
+	for (int i = 0; i < ARRAY_SIZE(advice_setting); i++) {
 		if (strcasecmp(k, advice_setting[i].key))
 			continue;
 		advice_setting[i].level = git_config_bool(var, value)
@@ -180,9 +179,7 @@ int git_default_advice_config(const char *var, const char *value)
 
 void list_config_advices(struct string_list *list, const char *prefix)
 {
-	int i;
-
-	for (i = 0; i < ARRAY_SIZE(advice_setting); i++)
+	for (int i = 0; i < ARRAY_SIZE(advice_setting); i++)
 		list_config_item(list, prefix, advice_setting[i].key);
 }
 
diff --git a/apply.c b/apply.c
index 355e2b0f2f..2b1582fa0e 100644
--- a/apply.c
+++ b/apply.c
@@ -504,7 +504,7 @@ static char *find_name_gnu(struct strbuf *root,
 
 static size_t sane_tz_len(const char *line, size_t len)
 {
-	const char *tz, *p;
+	const char *tz;
 
 	if (len < strlen(" +0500") || line[len-strlen(" +0500")] != ' ')
 		return 0;
@@ -513,7 +513,7 @@ static size_t sane_tz_len(const char *line, size_t len)
 	if (tz[1] != '+' && tz[1] != '-')
 		return 0;
 
-	for (p = tz + 2; p != line + len; p++)
+	for (const char *p = tz + 2; p != line + len; p++)
 		if (!isdigit(*p))
 			return 0;
 
@@ -801,13 +801,13 @@ static int has_epoch_timestamp(const char *nameline)
 		"^[0-2][0-9]:([0-5][0-9]):00(\\.0+)?"
 		" "
 		"([-+][0-2][0-9]:?[0-5][0-9])\n";
-	const char *timestamp = NULL, *cp, *colon;
+	const char *timestamp = NULL, *colon;
 	static regex_t *stamp;
 	regmatch_t m[10];
 	int zoneoffset, epoch_hour, hour, minute;
 	int status;
 
-	for (cp = nameline; *cp != '\n'; cp++) {
+	for (const char *cp = nameline; *cp != '\n'; cp++) {
 		if (*cp == '\t')
 			timestamp = cp + 1;
 	}
@@ -1144,13 +1144,12 @@ static const char *skip_tree_prefix(int p_value,
 				    int llen)
 {
 	int nslash;
-	int i;
 
 	if (!p_value)
 		return (llen && line[0] == '/') ? NULL : line;
 
 	nslash = p_value;
-	for (i = 0; i < llen; i++) {
+	for (int i = 0; i < llen; i++) {
 		int ch = line[i];
 		if (ch == '/' && --nslash <= 0)
 			return (i == 0) ? NULL : &line[i + 1];
@@ -1550,14 +1549,15 @@ static int find_header(struct apply_state *state,
 		       int *hdrsize,
 		       struct patch *patch)
 {
-	unsigned long offset, len;
+	unsigned long len;
 
 	patch->is_toplevel_relative = 0;
 	patch->is_rename = patch->is_copy = 0;
 	patch->is_new = patch->is_delete = -1;
 	patch->old_mode = patch->new_mode = 0;
 	patch->old_name = patch->new_name = NULL;
-	for (offset = 0; size > 0; offset += len, size -= len, line += len, state->linenr++) {
+	for (unsigned long offset = 0; size > 0; offset += len, size -= len,
+	     line += len, state->linenr++) {
 		unsigned long nextlen;
 
 		len = linelen(line, size);
@@ -2100,7 +2100,6 @@ static void add_name_limit(struct apply_state *state,
 static int use_patch(struct apply_state *state, struct patch *p)
 {
 	const char *pathname = p->new_name ? p->new_name : p->old_name;
-	int i;
 
 	/* Paths outside are not touched regardless of "--include" */
 	if (state->prefix && *state->prefix) {
@@ -2110,7 +2109,7 @@ static int use_patch(struct apply_state *state, struct patch *p)
 	}
 
 	/* See if it matches any of exclude/include rule */
-	for (i = 0; i < state->limit_by_name.nr; i++) {
+	for (int i = 0; i < state->limit_by_name.nr; i++) {
 		struct string_list_item *it = &state->limit_by_name.items[i];
 		if (!wildmatch(it->string, pathname, 0))
 			return (it->util != NULL);
@@ -2186,8 +2185,7 @@ static int parse_chunk(struct apply_state *state, char *buffer, unsigned long si
 				"Files ",
 				NULL,
 			};
-			int i;
-			for (i = 0; binhdr[i]; i++) {
+			for (int i = 0; binhdr[i]; i++) {
 				int len = strlen(binhdr[i]);
 				if (len < size - hd &&
 				    !memcmp(binhdr[i], buffer + hd, len)) {
@@ -4131,7 +4129,6 @@ static int preimage_oid_in_gitlink_patch(struct patch *p, struct object_id *oid)
 /* Build an index that contains just the files needed for a 3way merge */
 static int build_fake_ancestor(struct apply_state *state, struct patch *list)
 {
-	struct patch *patch;
 	struct index_state result = INDEX_STATE_INIT(state->repo);
 	struct lock_file lock = LOCK_INIT;
 	int res;
@@ -4139,7 +4136,7 @@ static int build_fake_ancestor(struct apply_state *state, struct patch *list)
 	/* Once we start supporting the reverse patch, it may be
 	 * worth showing the new sha1 prefix, but until then...
 	 */
-	for (patch = list; patch; patch = patch->next) {
+	for (struct patch *patch = list; patch; patch = patch->next) {
 		struct object_id oid;
 		struct cache_entry *ce;
 		const char *name;
@@ -4270,9 +4267,7 @@ static void show_rename_copy(struct patch *p)
 
 static void summary_patch_list(struct patch *patch)
 {
-	struct patch *p;
-
-	for (p = patch; p; p = p->next) {
+	for (struct patch *p = patch; p; p = p->next) {
 		if (p->is_new)
 			show_file_mode_name("create", p->new_mode, p->new_name);
 		else if (p->is_delete)
@@ -4524,7 +4519,7 @@ static int create_one_file(struct apply_state *state,
 static int add_conflicted_stages_file(struct apply_state *state,
 				       struct patch *patch)
 {
-	int stage, namelen;
+	int namelen;
 	unsigned mode;
 	struct cache_entry *ce;
 
@@ -4534,7 +4529,7 @@ static int add_conflicted_stages_file(struct apply_state *state,
 	mode = patch->new_mode ? patch->new_mode : (S_IFREG | 0644);
 
 	remove_file_from_index(state->repo->index, patch->new_name);
-	for (stage = 1; stage < 4; stage++) {
+	for (int stage = 1; stage < 4; stage++) {
 		if (is_null_oid(&patch->threeway_stage[stage - 1]))
 			continue;
 		ce = make_empty_cache_entry(state->repo->index, namelen);
@@ -4690,12 +4685,11 @@ static int write_out_one_reject(struct apply_state *state, struct patch *patch)
  */
 static int write_out_results(struct apply_state *state, struct patch *list)
 {
-	int phase;
 	int errs = 0;
 	struct patch *l;
 	struct string_list cpath = STRING_LIST_INIT_DUP;
 
-	for (phase = 0; phase < 2; phase++) {
+	for (int phase = 0; phase < 2; phase++) {
 		l = list;
 		while (l) {
 			if (l->rejected)
@@ -4967,12 +4961,11 @@ int apply_all_patches(struct apply_state *state,
 		      const char **argv,
 		      int options)
 {
-	int i;
 	int res;
 	int errs = 0;
 	int read_stdin = 1;
 
-	for (i = 0; i < argc; i++) {
+	for (int i = 0; i < argc; i++) {
 		const char *arg = argv[i];
 		char *to_free = NULL;
 		int fd;
diff --git a/archive-tar.c b/archive-tar.c
index 8ae30125f8..d5dcc342cd 100644
--- a/archive-tar.c
+++ b/archive-tar.c
@@ -157,11 +157,11 @@ static void strbuf_append_ext_header(struct strbuf *sb, const char *keyword,
 				     const char *value, size_t valuelen)
 {
 	size_t orig_len = sb->len;
-	size_t len, tmp;
+	size_t len;
 
 	/* "%u %s=%s\n" */
 	len = 1 + 1 + strlen(keyword) + 1 + valuelen + 1;
-	for (tmp = 1; len / 10 >= tmp; tmp *= 10)
+	for (size_t tmp = 1; len / 10 >= tmp; tmp *= 10)
 		len++;
 
 	strbuf_grow(sb, len);
@@ -362,8 +362,7 @@ static int alloc_tar_filters;
 
 static struct archiver *find_tar_filter(const char *name, size_t len)
 {
-	int i;
-	for (i = 0; i < nr_tar_filters; i++) {
+	for (int i = 0; i < nr_tar_filters; i++) {
 		struct archiver *ar = tar_filters[i];
 		if (!xstrncmpz(ar->name, name, len))
 			return ar;
@@ -531,7 +530,6 @@ static struct archiver tar_archiver = {
 
 void init_tar_archiver(void)
 {
-	int i;
 	register_archiver(&tar_archiver);
 
 	tar_filter_config("tar.tgz.command", internal_gzip_command, NULL);
@@ -539,7 +537,7 @@ void init_tar_archiver(void)
 	tar_filter_config("tar.tar.gz.command", internal_gzip_command, NULL);
 	tar_filter_config("tar.tar.gz.remote", "true", NULL);
 	git_config(git_tar_config, NULL);
-	for (i = 0; i < nr_tar_filters; i++) {
+	for (int i = 0; i < nr_tar_filters; i++) {
 		/* omit any filters that never had a command configured */
 		if (tar_filters[i]->filter_command)
 			register_archiver(tar_filters[i]);
diff --git a/archive.c b/archive.c
index a6730bebfa..ea30af9ffb 100644
--- a/archive.c
+++ b/archive.c
@@ -308,7 +308,6 @@ int write_archive_entries(struct archiver_args *args,
 	struct strbuf path_in_archive = STRBUF_INIT;
 	struct strbuf content = STRBUF_INIT;
 	struct object_id fake_oid;
-	int i;
 
 	oidcpy(&fake_oid, null_oid());
 
@@ -357,7 +356,7 @@ int write_archive_entries(struct archiver_args *args,
 		context.bottom = next;
 	}
 
-	for (i = 0; i < args->extra_files.nr; i++) {
+	for (int i = 0; i < args->extra_files.nr; i++) {
 		struct string_list_item *item = args->extra_files.items + i;
 		char *path = item->string;
 		struct extra_file_info *info = item->util;
@@ -396,12 +395,10 @@ int write_archive_entries(struct archiver_args *args,
 
 static const struct archiver *lookup_archiver(const char *name)
 {
-	int i;
-
 	if (!name)
 		return NULL;
 
-	for (i = 0; i < nr_archivers; i++) {
+	for (int i = 0; i < nr_archivers; i++) {
 		if (!strcmp(name, archivers[i]->name))
 			return archivers[i];
 	}
@@ -784,9 +781,7 @@ static int match_extension(const char *filename, const char *ext)
 
 const char *archive_format_from_filename(const char *filename)
 {
-	int i;
-
-	for (i = 0; i < nr_archivers; i++)
+	for (int i = 0; i < nr_archivers; i++)
 		if (match_extension(filename, archivers[i]->name))
 			return archivers[i]->name;
 	return NULL;
diff --git a/attr.c b/attr.c
index 679e42258c..af70c6a73f 100644
--- a/attr.c
+++ b/attr.c
@@ -142,7 +142,6 @@ struct all_attrs_item {
  */
 static void all_attrs_init(struct attr_hashmap *map, struct attr_check *check)
 {
-	int i;
 	unsigned int size;
 
 	hashmap_lock(map);
@@ -178,7 +177,7 @@ static void all_attrs_init(struct attr_hashmap *map, struct attr_check *check)
 	 * This re-initialization can live outside of the locked region since
 	 * the attribute dictionary is no longer being accessed.
 	 */
-	for (i = 0; i < check->all_attrs_nr; i++) {
+	for (int i = 0; i < check->all_attrs_nr; i++) {
 		check->all_attrs[i].value = ATTR__UNKNOWN;
 		check->all_attrs[i].macro = NULL;
 	}
@@ -471,9 +470,8 @@ struct attr_stack {
 
 static void attr_stack_free(struct attr_stack *e)
 {
-	unsigned i;
 	free(e->origin);
-	for (i = 0; i < e->num_matches; i++) {
+	for (unsigned i = 0; i < e->num_matches; i++) {
 		struct match_attr *a = e->attrs[i];
 		size_t j;
 
@@ -558,11 +556,9 @@ static void check_vector_remove(struct attr_check *check)
 /* Iterate through all attr_check instances and drop their stacks */
 static void drop_all_attr_stacks(void)
 {
-	int i;
-
 	vector_lock();
 
-	for (i = 0; i < check_vector.nr; i++) {
+	for (int i = 0; i < check_vector.nr; i++) {
 		drop_attr_stack(&check_vector.checks[i]->stack);
 	}
 
@@ -1102,9 +1098,7 @@ static int macroexpand_one(struct all_attrs_item *all_attrs, int nr, int rem);
 static int fill_one(struct all_attrs_item *all_attrs,
 		    const struct match_attr *a, int rem)
 {
-	size_t i;
-
-	for (i = a->num_attr; rem > 0 && i > 0; i--) {
+	for (size_t i = a->num_attr; rem > 0 && i > 0; i--) {
 		const struct git_attr *attr = a->state[i - 1].attr;
 		const char **n = &(all_attrs[attr->attr_nr].value);
 		const char *v = a->state[i - 1].setto;
@@ -1262,9 +1256,7 @@ static const char *interned_mode_string(unsigned int mode)
 		{ .val = 0120000 },
 		{ .val = 0160000 },
 	};
-	int i;
-
-	for (i = 0; i < ARRAY_SIZE(mode_string); i++) {
+	for (int i = 0; i < ARRAY_SIZE(mode_string); i++) {
 		if (mode_string[i].val != mode)
 			continue;
 		if (!*mode_string[i].str)
@@ -1333,12 +1325,11 @@ void git_check_attr(struct index_state *istate,
 		    const char *path,
 		    struct attr_check *check)
 {
-	int i;
 	const struct object_id *tree_oid = default_attr_source();
 
 	collect_some_attrs(istate, tree_oid, path, check);
 
-	for (i = 0; i < check->nr; i++) {
+	for (int i = 0; i < check->nr; i++) {
 		unsigned int n = check->items[i].attr->attr_nr;
 		const char *value = check->all_attrs[n].value;
 		if (value == ATTR__UNKNOWN)
@@ -1350,13 +1341,12 @@ void git_check_attr(struct index_state *istate,
 void git_all_attrs(struct index_state *istate,
 		   const char *path, struct attr_check *check)
 {
-	int i;
 	const struct object_id *tree_oid = default_attr_source();
 
 	attr_check_reset(check);
 	collect_some_attrs(istate, tree_oid, path, check);
 
-	for (i = 0; i < check->all_attrs_nr; i++) {
+	for (int i = 0; i < check->all_attrs_nr; i++) {
 		const char *name = check->all_attrs[i].attr->name;
 		const char *value = check->all_attrs[i].value;
 		struct attr_check_item *item;
diff --git a/base85.c b/base85.c
index bbacdca31b..0598e1c626 100644
--- a/base85.c
+++ b/base85.c
@@ -29,10 +29,9 @@ static const char en85[] = {
 static char de85[256];
 static void prep_base85(void)
 {
-	int i;
 	if (de85['Z'])
 		return;
-	for (i = 0; i < ARRAY_SIZE(en85); i++) {
+	for (int i = 0; i < ARRAY_SIZE(en85); i++) {
 		int ch = en85[i];
 		de85[ch] = i + 1;
 	}
diff --git a/bisect.c b/bisect.c
index f75e50c339..fe2d57c908 100644
--- a/bisect.c
+++ b/bisect.c
@@ -139,14 +139,12 @@ static inline int approx_halfway(struct commit_list *p, int nr)
 static void show_list(const char *debug, int counted, int nr,
 		      struct commit_list *list)
 {
-	struct commit_list *p;
-
 	if (!DEBUG_BISECT)
 		return;
 
 	fprintf(stderr, "%s (%d/%d)\n", debug, counted, nr);
 
-	for (p = list; p; p = p->next) {
+	for (struct commit_list *p = list; p; p = p->next) {
 		struct commit_list *pp;
 		struct commit *commit = p->item;
 		unsigned commit_flags = commit->object.flags;
@@ -183,11 +181,11 @@ static void show_list(const char *debug, int counted, int nr,
 
 static struct commit_list *best_bisection(struct commit_list *list, int nr)
 {
-	struct commit_list *p, *best;
+	struct commit_list *best;
 	int best_distance = -1;
 
 	best = list;
-	for (p = list; p; p = p->next) {
+	for (struct commit_list *p = list; p; p = p->next) {
 		int distance;
 		unsigned commit_flags = p->item->object.flags;
 
@@ -500,9 +498,7 @@ static void read_bisect_paths(struct strvec *array)
 static char *join_oid_array_hex(struct oid_array *array, char delim)
 {
 	struct strbuf joined_hexs = STRBUF_INIT;
-	int i;
-
-	for (i = 0; i < array->nr; i++) {
+	for (int i = 0; i < array->nr; i++) {
 		strbuf_addstr(&joined_hexs, oid_to_hex(array->oid + i));
 		if (i + 1 < array->nr)
 			strbuf_addch(&joined_hexs, delim);
@@ -611,7 +607,7 @@ static int sqrti(int val)
 static struct commit_list *skip_away(struct commit_list *list, int count)
 {
 	struct commit_list *cur, *previous;
-	int prn, index, i;
+	int prn, index;
 
 	prn = get_prn(count);
 	index = (count * prn / PRN_MODULO) * sqrti(prn) / sqrti(PRN_MODULO);
@@ -619,7 +615,7 @@ static struct commit_list *skip_away(struct commit_list *list, int count)
 	cur = list;
 	previous = NULL;
 
-	for (i = 0; cur; cur = cur->next, i++) {
+	for (int i = 0; cur; cur = cur->next, i++) {
 		if (i == index) {
 			if (!oideq(&cur->item->object.oid, current_bad_oid))
 				return cur;
@@ -660,7 +656,6 @@ static void bisect_rev_setup(struct repository *r, struct rev_info *revs,
 	struct setup_revision_opt opt = {
 		.free_removed_argv_elements = 1,
 	};
-	int i;
 
 	repo_init_revisions(r, revs, prefix);
 	revs->abbrev = 0;
@@ -669,7 +664,7 @@ static void bisect_rev_setup(struct repository *r, struct rev_info *revs,
 	/* rev_argv.argv[0] will be ignored by setup_revisions */
 	strvec_push(rev_argv, "bisect_rev_setup");
 	strvec_pushf(rev_argv, bad_format, oid_to_hex(current_bad_oid));
-	for (i = 0; i < good_revs.nr; i++)
+	for (int i = 0; i < good_revs.nr; i++)
 		strvec_pushf(rev_argv, good_format,
 			     oid_to_hex(good_revs.oid + i));
 	strvec_push(rev_argv, "--");
@@ -763,11 +758,11 @@ static struct commit **get_bad_and_good_commits(struct repository *r,
 						int *rev_nr)
 {
 	struct commit **rev;
-	int i, n = 0;
+	int n = 0;
 
 	ALLOC_ARRAY(rev, 1 + good_revs.nr);
 	rev[n++] = get_commit_reference(r, current_bad_oid);
-	for (i = 0; i < good_revs.nr; i++)
+	for (int i = 0; i < good_revs.nr; i++)
 		rev[n++] = get_commit_reference(r, good_revs.oid + i);
 	*rev_nr = n;
 
diff --git a/blame.c b/blame.c
index 1a16d4eb6a..c15162591e 100644
--- a/blame.c
+++ b/blame.c
@@ -41,12 +41,13 @@ static void set_blame_suspects(struct commit *commit, struct blame_origin *origi
 void blame_origin_decref(struct blame_origin *o)
 {
 	if (o && --o->refcnt <= 0) {
-		struct blame_origin *p, *l = NULL;
+		struct blame_origin *l = NULL;
 		if (o->previous)
 			blame_origin_decref(o->previous);
 		free(o->file.ptr);
 		/* Should be present exactly once in commit chain */
-		for (p = get_blame_suspects(o->commit); p; l = p, p = p->next) {
+		for (struct blame_origin *p = get_blame_suspects(o->commit); p; l = p,
+		     p = p->next) {
 			if (p == o) {
 				if (l)
 					l->next = p->next;
@@ -104,10 +105,9 @@ static struct blame_origin *get_origin(struct commit *commit, const char *path)
 static void verify_working_tree_path(struct repository *r,
 				     struct commit *work_tree, const char *path)
 {
-	struct commit_list *parents;
 	int pos;
 
-	for (parents = work_tree->parents; parents; parents = parents->next) {
+	for (struct commit_list *parents = work_tree->parents; parents; parents = parents->next) {
 		const struct object_id *commit_oid = &parents->item->object.oid;
 		struct object_id blob_oid;
 		unsigned short mode;
@@ -190,7 +190,7 @@ static struct commit *fake_working_tree_commit(struct repository *r,
 {
 	struct commit *commit;
 	struct blame_origin *origin;
-	struct commit_list **parent_tail, *parent;
+	struct commit_list **parent_tail;
 	struct strbuf buf = STRBUF_INIT;
 	const char *ident;
 	time_t now;
@@ -219,7 +219,7 @@ static struct commit *fake_working_tree_commit(struct repository *r,
 		ident = fmt_ident("Not Committed Yet", "not.committed.yet",
 				  WANT_BLANK_IDENT, NULL, 0);
 	strbuf_addstr(&msg, "tree 0000000000000000000000000000000000000000\n");
-	for (parent = commit->parents; parent; parent = parent->next)
+	for (struct commit_list *parent = commit->parents; parent; parent = parent->next)
 		strbuf_addf(&msg, "parent %s\n",
 			    oid_to_hex(&parent->item->object.oid));
 	strbuf_addf(&msg,
@@ -407,7 +407,6 @@ static void get_fingerprint(struct fingerprint *result,
 			    const char *line_end)
 {
 	unsigned int hash, c0 = 0, c1;
-	const char *p;
 	int max_map_entry_count = 1 + line_end - line_begin;
 	struct fingerprint_entry *entry = xcalloc(max_map_entry_count,
 		sizeof(struct fingerprint_entry));
@@ -415,7 +414,7 @@ static void get_fingerprint(struct fingerprint *result,
 
 	hashmap_init(&result->map, NULL, NULL, max_map_entry_count);
 	result->entries = entry;
-	for (p = line_begin; p <= line_end; ++p, c0 = c1) {
+	for (const char *p = line_begin; p <= line_end; ++p, c0 = c1) {
 		/* Always terminate the string with whitespace.
 		 * Normalise whitespace to 0, and normalise letters to
 		 * lower case. This won't work for multibyte characters but at
@@ -503,11 +502,10 @@ static void get_line_fingerprints(struct fingerprint *fingerprints,
 				  const char *content, const int *line_starts,
 				  long first_line, long line_count)
 {
-	int i;
 	const char *linestart, *lineend;
 
 	line_starts += first_line;
-	for (i = 0; i < line_count; ++i) {
+	for (int i = 0; i < line_count; ++i) {
 		linestart = content + line_starts[i];
 		lineend = content + line_starts[i + 1];
 		get_fingerprint(fingerprints + i, linestart, lineend);
@@ -517,9 +515,7 @@ static void get_line_fingerprints(struct fingerprint *fingerprints,
 static void free_line_fingerprints(struct fingerprint *fingerprints,
 				   int nr_fingerprints)
 {
-	int i;
-
-	for (i = 0; i < nr_fingerprints; i++)
+	for (int i = 0; i < nr_fingerprints; i++)
 		free_fingerprint(&fingerprints[i]);
 }
 
@@ -644,7 +640,7 @@ static void find_best_line_matches(
 	const struct line_number_mapping *map_line_number_in_b_to_a)
 {
 
-	int i, search_start, search_end, closest_local_line_a, *similarity,
+	int search_start, search_end, closest_local_line_a, *similarity,
 		best_similarity = 0, second_best_similarity = 0,
 		best_similarity_index = 0, second_best_similarity_index = 0;
 
@@ -663,7 +659,7 @@ static void find_best_line_matches(
 	if (search_end > length_a)
 		search_end = length_a;
 
-	for (i = search_start; i < search_end; ++i) {
+	for (int i = search_start; i < search_end; ++i) {
 		similarity = get_similarity(similarities,
 					    i, local_line_b,
 					    closest_local_line_a,
@@ -1158,9 +1154,7 @@ static int compare_commits_by_reverse_commit_date(const void *a,
 static void sanity_check_refcnt(struct blame_scoreboard *sb)
 {
 	int baa = 0;
-	struct blame_entry *ent;
-
-	for (ent = sb->ent; ent; ent = ent->next) {
+	for (struct blame_entry *ent = sb->ent; ent; ent = ent->next) {
 		/* Nobody should have zero or negative refcnt */
 		if (ent->suspect->refcnt <= 0) {
 			fprintf(stderr, "%s in %s has negative refcnt %d\n",
@@ -1181,9 +1175,9 @@ static void sanity_check_refcnt(struct blame_scoreboard *sb)
  */
 void blame_coalesce(struct blame_scoreboard *sb)
 {
-	struct blame_entry *ent, *next;
+	struct blame_entry *next;
 
-	for (ent = sb->ent; ent && (next = ent->next); ent = next) {
+	for (struct blame_entry *ent = sb->ent; ent && (next = ent->next); ent = next) {
 		if (ent->suspect == next->suspect &&
 		    ent->s_lno + ent->num_lines == next->s_lno &&
 		    ent->lno + ent->num_lines == next->lno &&
@@ -1214,8 +1208,7 @@ static void queue_blames(struct blame_scoreboard *sb, struct blame_origin *porig
 	if (porigin->suspects)
 		porigin->suspects = blame_merge(porigin->suspects, sorted);
 	else {
-		struct blame_origin *o;
-		for (o = get_blame_suspects(porigin->commit); o; o = o->next) {
+		for (struct blame_origin *o = get_blame_suspects(porigin->commit); o; o = o->next) {
 			if (o->suspects) {
 				porigin->suspects = sorted;
 				return;
@@ -1269,7 +1262,6 @@ static int maybe_changed_path(struct repository *r,
 			      struct blame_origin *origin,
 			      struct blame_bloom_data *bd)
 {
-	int i;
 	struct bloom_filter *filter;
 
 	if (!bd)
@@ -1284,7 +1276,7 @@ static int maybe_changed_path(struct repository *r,
 		return 1;
 
 	bloom_count_queries++;
-	for (i = 0; i < bd->nr; i++) {
+	for (int i = 0; i < bd->nr; i++) {
 		if (bloom_filter_contains(filter,
 					  bd->keys[i],
 					  bd->settings))
@@ -1372,15 +1364,8 @@ static struct blame_origin *find_origin(struct repository *r,
 		oidcpy(&porigin->blob_oid, &origin->blob_oid);
 		porigin->mode = origin->mode;
 	} else {
-		/*
-		 * Since origin->path is a pathspec, if the parent
-		 * commit had it as a directory, we will see a whole
-		 * bunch of deletion of files in the directory that we
-		 * do not care about.
-		 */
-		int i;
 		struct diff_filepair *p = NULL;
-		for (i = 0; i < diff_queued_diff.nr; i++) {
+		for (int i = 0; i < diff_queued_diff.nr; i++) {
 			const char *name;
 			p = diff_queued_diff.queue[i];
 			name = p->one->path ? p->one->path : p->two->path;
@@ -1419,7 +1404,6 @@ static struct blame_origin *find_rename(struct repository *r,
 {
 	struct blame_origin *porigin = NULL;
 	struct diff_options diff_opts;
-	int i;
 
 	repo_diff_setup(r, &diff_opts);
 	diff_opts.flags.recursive = 1;
@@ -1436,7 +1420,7 @@ static struct blame_origin *find_rename(struct repository *r,
 			      "", &diff_opts);
 	diffcore_std(&diff_opts);
 
-	for (i = 0; i < diff_queued_diff.nr; i++) {
+	for (int i = 0; i < diff_queued_diff.nr; i++) {
 		struct diff_filepair *p = diff_queued_diff.queue[i];
 		if ((p->status == 'R' || p->status == 'C') &&
 		    !strcmp(p->two->path, origin->path)) {
@@ -1507,10 +1491,9 @@ static void split_overlap(struct blame_entry *split,
 			  struct blame_origin *parent)
 {
 	int chunk_end_lno;
-	int i;
 	memset(split, 0, sizeof(struct blame_entry [3]));
 
-	for (i = 0; i < 3; i++) {
+	for (int i = 0; i < 3; i++) {
 		split[i].ignored = e->ignored;
 		split[i].unblamable = e->unblamable;
 	}
@@ -1594,9 +1577,7 @@ static void split_blame(struct blame_entry ***blamed,
  */
 static void decref_split(struct blame_entry *split)
 {
-	int i;
-
-	for (i = 0; i < 3; i++)
+	for (int i = 0; i < 3; i++)
 		blame_origin_decref(split[i].suspect);
 }
 
@@ -1661,12 +1642,12 @@ static int scan_parent_range(struct fingerprint *p_fps,
 			     struct fingerprint *t_fps, int t_idx,
 			     int from, int nr_lines)
 {
-	int sim, p_idx;
+	int sim;
 	#define FINGERPRINT_FILE_THRESHOLD	10
 	int best_sim_val = FINGERPRINT_FILE_THRESHOLD;
 	int best_sim_idx = -1;
 
-	for (p_idx = from; p_idx < from + nr_lines; p_idx++) {
+	for (int p_idx = from; p_idx < from + nr_lines; p_idx++) {
 		sim = fingerprint_similarity(&t_fps[t_idx], &p_fps[p_idx]);
 		if (sim < best_sim_val)
 			continue;
@@ -1691,14 +1672,14 @@ static void guess_line_blames(struct blame_origin *parent,
 			      int tlno, int offset, int same, int parent_len,
 			      struct blame_line_tracker *line_blames)
 {
-	int i, best_idx, target_idx;
+	int best_idx, target_idx;
 	int parent_slno = tlno + offset;
 	int *fuzzy_matches;
 
 	fuzzy_matches = fuzzy_find_matching_lines(parent, target,
 						  tlno, parent_slno, same,
 						  parent_len);
-	for (i = 0; i < same - tlno; i++) {
+	for (int i = 0; i < same - tlno; i++) {
 		target_idx = tlno + i;
 		if (fuzzy_matches && fuzzy_matches[i] >= 0) {
 			best_idx = fuzzy_matches[i];
@@ -1735,7 +1716,7 @@ static void ignore_blame_entry(struct blame_entry *e,
 			       struct blame_entry **ignoredp,
 			       struct blame_line_tracker *line_blames)
 {
-	int entry_len, nr_lines, i;
+	int entry_len, nr_lines;
 
 	/*
 	 * We carve new entries off the front of e.  Each entry comes from a
@@ -1744,7 +1725,7 @@ static void ignore_blame_entry(struct blame_entry *e,
 	 */
 	entry_len = 1;
 	nr_lines = e->num_lines;	/* e changes in the loop */
-	for (i = 0; i < nr_lines; i++) {
+	for (int i = 0; i < nr_lines; i++) {
 		struct blame_entry *next = NULL;
 
 		/*
@@ -2012,8 +1993,6 @@ static void copy_split_if_better(struct blame_scoreboard *sb,
 				 struct blame_entry *best_so_far,
 				 struct blame_entry *potential)
 {
-	int i;
-
 	if (!potential[1].suspect)
 		return;
 	if (best_so_far[1].suspect) {
@@ -2022,7 +2001,7 @@ static void copy_split_if_better(struct blame_scoreboard *sb,
 			return;
 	}
 
-	for (i = 0; i < 3; i++)
+	for (int i = 0; i < 3; i++)
 		blame_origin_incref(potential[i].suspect);
 	decref_split(best_so_far);
 	memcpy(best_so_far, potential, sizeof(struct blame_entry[3]));
@@ -2335,7 +2314,7 @@ static void find_copy_in_parent(struct blame_scoreboard *sb,
 static void pass_whole_blame(struct blame_scoreboard *sb,
 			     struct blame_origin *origin, struct blame_origin *porigin)
 {
-	struct blame_entry *e, *suspects;
+	struct blame_entry *suspects;
 
 	if (!porigin->file.ptr && origin->file.ptr) {
 		/* Steal its file */
@@ -2344,7 +2323,7 @@ static void pass_whole_blame(struct blame_scoreboard *sb,
 	}
 	suspects = origin->suspects;
 	origin->suspects = NULL;
-	for (e = suspects; e; e = e->next) {
+	for (struct blame_entry *e = suspects; e; e = e->next) {
 		blame_origin_incref(porigin);
 		blame_origin_decref(e->suspect);
 		e->suspect = porigin;
@@ -2409,7 +2388,7 @@ typedef struct blame_origin *(*blame_find_alg)(struct repository *,
 static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin, int opt)
 {
 	struct rev_info *revs = sb->revs;
-	int i, pass, num_sg;
+	int i, num_sg;
 	struct commit *commit = origin->commit;
 	struct commit_list *sg;
 	struct blame_origin *sg_buf[MAXSG];
@@ -2429,7 +2408,7 @@ static void pass_blame(struct blame_scoreboard *sb, struct blame_origin *origin,
 	 * The first pass looks for unrenamed path to optimize for
 	 * common cases, then we look for renames in the second pass.
 	 */
-	for (pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {
+	for (int pass = 0; pass < 2 - sb->no_whole_file_rename; pass++) {
 		blame_find_alg find = pass ? find_rename : find_origin;
 
 		for (i = 0, sg = first_scapegoat(revs, commit, sb->reverse);
@@ -2656,11 +2635,10 @@ static int prepare_lines(struct blame_scoreboard *sb)
 static struct commit *find_single_final(struct rev_info *revs,
 					const char **name_p)
 {
-	int i;
 	struct commit *found = NULL;
 	const char *name = NULL;
 
-	for (i = 0; i < revs->pending.nr; i++) {
+	for (int i = 0; i < revs->pending.nr; i++) {
 		struct object *obj = revs->pending.objects[i].item;
 		if (obj->flags & UNINTERESTING)
 			continue;
@@ -2719,7 +2697,6 @@ static struct commit *dwim_reverse_initial(struct rev_info *revs,
 static struct commit *find_single_initial(struct rev_info *revs,
 					  const char **name_p)
 {
-	int i;
 	struct commit *found = NULL;
 	const char *name = NULL;
 
@@ -2727,7 +2704,7 @@ static struct commit *find_single_initial(struct rev_info *revs,
 	 * There must be one and only one negative commit, and it must be
 	 * the boundary.
 	 */
-	for (i = 0; i < revs->pending.nr; i++) {
+	for (int i = 0; i < revs->pending.nr; i++) {
 		struct object *obj = revs->pending.objects[i].item;
 		if (!(obj->flags & UNINTERESTING))
 			continue;
@@ -2929,8 +2906,7 @@ void setup_blame_bloom_data(struct blame_scoreboard *sb)
 void cleanup_scoreboard(struct blame_scoreboard *sb)
 {
 	if (sb->bloom_data) {
-		int i;
-		for (i = 0; i < sb->bloom_data->nr; i++) {
+		for (int i = 0; i < sb->bloom_data->nr; i++) {
 			free(sb->bloom_data->keys[i]->hashes);
 			free(sb->bloom_data->keys[i]);
 		}
diff --git a/bloom.c b/bloom.c
index e529f7605c..58bb79e62c 100644
--- a/bloom.c
+++ b/bloom.c
@@ -107,14 +107,13 @@ uint32_t murmur3_seeded(uint32_t seed, const char *data, size_t len)
 	const uint32_t r2 = 13;
 	const uint32_t m = 5;
 	const uint32_t n = 0xe6546b64;
-	int i;
 	uint32_t k1 = 0;
 	const char *tail;
 
 	int len4 = len / sizeof(uint32_t);
 
 	uint32_t k;
-	for (i = 0; i < len4; i++) {
+	for (int i = 0; i < len4; i++) {
 		uint32_t byte1 = (uint32_t)data[4*i];
 		uint32_t byte2 = ((uint32_t)data[4*i + 1]) << 8;
 		uint32_t byte3 = ((uint32_t)data[4*i + 2]) << 16;
@@ -161,14 +160,13 @@ void fill_bloom_key(const char *data,
 		    struct bloom_key *key,
 		    const struct bloom_filter_settings *settings)
 {
-	int i;
 	const uint32_t seed0 = 0x293ae76f;
 	const uint32_t seed1 = 0x7e646e2c;
 	const uint32_t hash0 = murmur3_seeded(seed0, data, len);
 	const uint32_t hash1 = murmur3_seeded(seed1, data, len);
 
 	key->hashes = (uint32_t *)xcalloc(settings->num_hashes, sizeof(uint32_t));
-	for (i = 0; i < settings->num_hashes; i++)
+	for (int i = 0; i < settings->num_hashes; i++)
 		key->hashes[i] = hash0 + i * hash1;
 }
 
@@ -181,10 +179,9 @@ void add_key_to_filter(const struct bloom_key *key,
 		       struct bloom_filter *filter,
 		       const struct bloom_filter_settings *settings)
 {
-	int i;
 	uint64_t mod = filter->len * BITS_PER_WORD;
 
-	for (i = 0; i < settings->num_hashes; i++) {
+	for (int i = 0; i < settings->num_hashes; i++) {
 		uint64_t hash_mod = key->hashes[i] % mod;
 		uint64_t block_pos = hash_mod / BITS_PER_WORD;
 
@@ -224,7 +221,6 @@ struct bloom_filter *get_or_compute_bloom_filter(struct repository *r,
 						 enum bloom_filter_computed *computed)
 {
 	struct bloom_filter *filter;
-	int i;
 	struct diff_options diffopt;
 
 	if (computed)
@@ -267,7 +263,7 @@ struct bloom_filter *get_or_compute_bloom_filter(struct repository *r,
 		struct pathmap_hash_entry *e;
 		struct hashmap_iter iter;
 
-		for (i = 0; i < diff_queued_diff.nr; i++) {
+		for (int i = 0; i < diff_queued_diff.nr; i++) {
 			const char *path = diff_queued_diff.queue[i]->two->path;
 
 			/*
@@ -323,7 +319,7 @@ struct bloom_filter *get_or_compute_bloom_filter(struct repository *r,
 	cleanup:
 		hashmap_clear_and_free(&pathmap, struct pathmap_hash_entry, entry);
 	} else {
-		for (i = 0; i < diff_queued_diff.nr; i++)
+		for (int i = 0; i < diff_queued_diff.nr; i++)
 			diff_free_filepair(diff_queued_diff.queue[i]);
 		init_truncated_large_filter(filter);
 
@@ -344,13 +340,12 @@ int bloom_filter_contains(const struct bloom_filter *filter,
 			  const struct bloom_key *key,
 			  const struct bloom_filter_settings *settings)
 {
-	int i;
 	uint64_t mod = filter->len * BITS_PER_WORD;
 
 	if (!mod)
 		return -1;
 
-	for (i = 0; i < settings->num_hashes; i++) {
+	for (int i = 0; i < settings->num_hashes; i++) {
 		uint64_t hash_mod = key->hashes[i] % mod;
 		uint64_t block_pos = hash_mod / BITS_PER_WORD;
 		if (!(filter->data[block_pos] & get_bitmask(hash_mod)))
diff --git a/branch.c b/branch.c
index 6719a181bd..a2b56f701a 100644
--- a/branch.c
+++ b/branch.c
@@ -216,7 +216,6 @@ static int inherit_tracking(struct tracking *tracking, const char *orig_ref)
 {
 	const char *bare_ref;
 	struct branch *branch;
-	int i;
 
 	bare_ref = orig_ref;
 	skip_prefix(orig_ref, "refs/heads/", &bare_ref);
@@ -235,7 +234,7 @@ static int inherit_tracking(struct tracking *tracking, const char *orig_ref)
 	}
 
 	tracking->remote = branch->remote_name;
-	for (i = 0; i < branch->merge_nr; i++)
+	for (int i = 0; i < branch->merge_nr; i++)
 		string_list_append(tracking->srcs, branch->merge_name[i]);
 	return 0;
 }
diff --git a/builtin/add.c b/builtin/add.c
index ada7719561..07052ef827 100644
--- a/builtin/add.c
+++ b/builtin/add.c
@@ -38,9 +38,9 @@ static const char *pathspec_from_file;
 
 static int chmod_pathspec(struct pathspec *pathspec, char flip, int show_only)
 {
-	int i, ret = 0;
+	int ret = 0;
 
-	for (i = 0; i < the_index.cache_nr; i++) {
+	for (int i = 0; i < the_index.cache_nr; i++) {
 		struct cache_entry *ce = the_index.cache[i];
 		int err;
 
@@ -66,9 +66,9 @@ static int chmod_pathspec(struct pathspec *pathspec, char flip, int show_only)
 
 static int renormalize_tracked_files(const struct pathspec *pathspec, int flags)
 {
-	int i, retval = 0;
+	int retval = 0;
 
-	for (i = 0; i < the_index.cache_nr; i++) {
+	for (int i = 0; i < the_index.cache_nr; i++) {
 		struct cache_entry *ce = the_index.cache[i];
 
 		if (!include_sparse &&
@@ -112,7 +112,7 @@ static char *prune_directory(struct dir_struct *dir, struct pathspec *pathspec,
 static int refresh(int verbose, const struct pathspec *pathspec)
 {
 	char *seen;
-	int i, ret = 0;
+	int ret = 0;
 	char *skip_worktree_seen = NULL;
 	struct string_list only_match_skip_worktree = STRING_LIST_INIT_NODUP;
 	int flags = REFRESH_IGNORE_SKIP_WORKTREE |
@@ -121,7 +121,7 @@ static int refresh(int verbose, const struct pathspec *pathspec)
 	seen = xcalloc(pathspec->nr, 1);
 	refresh_index(&the_index, flags, pathspec, seen,
 		      _("Unstaged changes after refreshing the index:"));
-	for (i = 0; i < pathspec->nr; i++) {
+	for (int i = 0; i < pathspec->nr; i++) {
 		if (!seen[i]) {
 			const char *path = pathspec->items[i].original;
 
@@ -485,7 +485,6 @@ int cmd_add(int argc, const char **argv, const char *prefix)
 	}
 
 	if (pathspec.nr) {
-		int i;
 		char *skip_worktree_seen = NULL;
 		struct string_list only_match_skip_worktree = STRING_LIST_INIT_NODUP;
 
@@ -504,7 +503,7 @@ int cmd_add(int argc, const char **argv, const char *prefix)
 			       PATHSPEC_EXCLUDE |
 			       PATHSPEC_ATTR);
 
-		for (i = 0; i < pathspec.nr; i++) {
+		for (int i = 0; i < pathspec.nr; i++) {
 			const char *path = pathspec.items[i].match;
 
 			if (pathspec.items[i].magic & PATHSPEC_EXCLUDE)
diff --git a/builtin/am.c b/builtin/am.c
index d1990d7edc..512e2a150d 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -2445,7 +2445,6 @@ int cmd_am(int argc, const char **argv, const char *prefix)
 			am_append_signoff(&state);
 	} else {
 		struct strvec paths = STRVEC_INIT;
-		int i;
 
 		/*
 		 * Handle stray state directory in the independent-run case. In
@@ -2467,7 +2466,7 @@ int cmd_am(int argc, const char **argv, const char *prefix)
 		if (resume_mode)
 			die(_("Resolve operation not in progress, we are not resuming."));
 
-		for (i = 0; i < argc; i++) {
+		for (int i = 0; i < argc; i++) {
 			if (is_absolute_path(argv[i]) || !prefix)
 				strvec_push(&paths, argv[i]);
 			else
diff --git a/builtin/annotate.c b/builtin/annotate.c
index 58ff977a23..a940f50573 100644
--- a/builtin/annotate.c
+++ b/builtin/annotate.c
@@ -10,11 +10,10 @@
 int cmd_annotate(int argc, const char **argv, const char *prefix)
 {
 	struct strvec args = STRVEC_INIT;
-	int i;
 
 	strvec_pushl(&args, "annotate", "-c", NULL);
 
-	for (i = 1; i < argc; i++) {
+	for (int i = 1; i < argc; i++) {
 		strvec_push(&args, argv[i]);
 	}
 
diff --git a/builtin/archive.c b/builtin/archive.c
index 15ee1ec7bb..34db16787e 100644
--- a/builtin/archive.c
+++ b/builtin/archive.c
@@ -25,7 +25,7 @@ static int run_remote_archiver(int argc, const char **argv,
 			       const char *remote, const char *exec,
 			       const char *name_hint)
 {
-	int fd[2], i, rv;
+	int fd[2], rv;
 	struct transport *transport;
 	struct remote *_remote;
 	struct packet_reader reader;
@@ -47,7 +47,7 @@ static int run_remote_archiver(int argc, const char **argv,
 		if (format)
 			packet_write_fmt(fd[1], "argument --format=%s\n", format);
 	}
-	for (i = 1; i < argc; i++)
+	for (int i = 1; i < argc; i++)
 		packet_write_fmt(fd[1], "argument %s\n", argv[i]);
 	packet_flush(fd[1]);
 
diff --git a/builtin/bisect.c b/builtin/bisect.c
index f69c3f7e43..74a417f334 100644
--- a/builtin/bisect.c
+++ b/builtin/bisect.c
@@ -916,7 +916,7 @@ static enum bisect_error bisect_state(struct bisect_terms *terms, int argc,
 				      const char **argv)
 {
 	const char *state;
-	int i, verify_expected = 1;
+	int verify_expected = 1;
 	struct object_id oid, expected;
 	struct oid_array revs = OID_ARRAY_INIT;
 
@@ -975,7 +975,7 @@ static enum bisect_error bisect_state(struct bisect_terms *terms, int argc,
 	if (read_ref("BISECT_EXPECTED_REV", &expected))
 		verify_expected = 0; /* Ignore invalid file contents */
 
-	for (i = 0; i < revs.nr; i++) {
+	for (int i = 0; i < revs.nr; i++) {
 		if (bisect_write(state, oid_to_hex(&revs.oid[i]), terms, 0)) {
 			oid_array_clear(&revs);
 			return BISECT_FAILED;
@@ -1083,13 +1083,12 @@ static enum bisect_error bisect_replay(struct bisect_terms *terms, const char *f
 static enum bisect_error bisect_skip(struct bisect_terms *terms, int argc,
 				     const char **argv)
 {
-	int i;
 	enum bisect_error res;
 	struct strvec argv_state = STRVEC_INIT;
 
 	strvec_push(&argv_state, "skip");
 
-	for (i = 0; i < argc; i++) {
+	for (int i = 0; i < argc; i++) {
 		const char *dotdot = strstr(argv[i], "..");
 
 		if (dotdot) {
diff --git a/builtin/blame.c b/builtin/blame.c
index db1f56de61..b36e9bee72 100644
--- a/builtin/blame.c
+++ b/builtin/blame.c
@@ -313,7 +313,6 @@ static const char *format_time(timestamp_t time, const char *tz_str,
 	}
 	else {
 		const char *time_str;
-		size_t time_width;
 		int tz;
 		tz = atoi(tz_str);
 		time_str = show_date(time, tz, &blame_date_mode);
@@ -322,9 +321,7 @@ static const char *format_time(timestamp_t time, const char *tz_str,
 		 * Add space paddings to time_buf to display a fixed width
 		 * string, and use time_width for display width calibration.
 		 */
-		for (time_width = utf8_strwidth(time_str);
-		     time_width < blame_date_width;
-		     time_width++)
+		for (size_t time_width = utf8_strwidth(time_str); time_width < blame_date_width; time_width++)
 			strbuf_addch(&time_buf, ' ');
 	}
 	return time_buf.buf;
@@ -354,7 +351,6 @@ static void emit_porcelain(struct blame_scoreboard *sb, struct blame_entry *ent,
 			   int opt)
 {
 	int repeat = opt & OUTPUT_LINE_PORCELAIN;
-	int cnt;
 	const char *cp;
 	struct blame_origin *suspect = ent->suspect;
 	char hex[GIT_MAX_HEXSZ + 1];
@@ -368,7 +364,7 @@ static void emit_porcelain(struct blame_scoreboard *sb, struct blame_entry *ent,
 	emit_porcelain_details(suspect, repeat);
 
 	cp = blame_nth_line(sb, ent->lno);
-	for (cnt = 0; cnt < ent->num_lines; cnt++) {
+	for (int cnt = 0; cnt < ent->num_lines; cnt++) {
 		char ch;
 		if (cnt) {
 			printf("%s %d %d\n", hex,
@@ -447,7 +443,6 @@ static void determine_line_heat(struct commit_info *ci, const char **dest_color)
 
 static void emit_other(struct blame_scoreboard *sb, struct blame_entry *ent, int opt)
 {
-	int cnt;
 	const char *cp;
 	struct blame_origin *suspect = ent->suspect;
 	struct commit_info ci = COMMIT_INFO_INIT;
@@ -466,7 +461,7 @@ static void emit_other(struct blame_scoreboard *sb, struct blame_entry *ent, int
 		reset = GIT_COLOR_RESET;
 	}
 
-	for (cnt = 0; cnt < ent->num_lines; cnt++) {
+	for (int cnt = 0; cnt < ent->num_lines; cnt++) {
 		char ch;
 		int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? the_hash_algo->hexsz : abbrev;
 
@@ -625,11 +620,10 @@ static void find_alignment(struct blame_scoreboard *sb, int *option)
 	int longest_src_lines = 0;
 	int longest_dst_lines = 0;
 	unsigned largest_score = 0;
-	struct blame_entry *e;
 	int compute_auto_abbrev = (abbrev < 0);
 	int auto_abbrev = DEFAULT_ABBREV;
 
-	for (e = sb->ent; e; e = e->next) {
+	for (struct blame_entry *e = sb->ent; e; e = e->next) {
 		struct blame_origin *suspect = e->suspect;
 		int num;
 
diff --git a/builtin/branch.c b/builtin/branch.c
index cfb63cce5f..774e213461 100644
--- a/builtin/branch.c
+++ b/builtin/branch.c
@@ -216,7 +216,6 @@ static int delete_branches(int argc, const char **argv, int force, int kinds,
 	struct object_id oid;
 	char *name = NULL;
 	const char *fmt;
-	int i;
 	int ret = 0;
 	int remote_branch = 0;
 	struct strbuf bname = STRBUF_INIT;
@@ -247,7 +246,7 @@ static int delete_branches(int argc, const char **argv, int force, int kinds,
 	if (!force)
 		head_rev = lookup_commit_reference(the_repository, &head_oid);
 
-	for (i = 0; i < argc; i++, strbuf_reset(&bname)) {
+	for (int i = 0; i < argc; i++, strbuf_reset(&bname)) {
 		char *target = NULL;
 		int flags = 0;
 
@@ -339,8 +338,8 @@ static int delete_branches(int argc, const char **argv, int force, int kinds,
 
 static int calc_maxwidth(struct ref_array *refs, int remote_bonus)
 {
-	int i, max = 0;
-	for (i = 0; i < refs->nr; i++) {
+	int max = 0;
+	for (int i = 0; i < refs->nr; i++) {
 		struct ref_array_item *it = refs->items[i];
 		const char *desc = it->refname;
 		int w;
@@ -508,9 +507,7 @@ static void print_current_branch_name(void)
 static void reject_rebase_or_bisect_branch(struct worktree **worktrees,
 					   const char *target)
 {
-	int i;
-
-	for (i = 0; worktrees[i]; i++) {
+	for (int i = 0; worktrees[i]; i++) {
 		struct worktree *wt = worktrees[i];
 
 		if (!wt->is_detached)
@@ -536,9 +533,7 @@ static int replace_each_worktree_head_symref(struct worktree **worktrees,
 					     const char *logmsg)
 {
 	int ret = 0;
-	int i;
-
-	for (i = 0; worktrees[i]; i++) {
+	for (int i = 0; worktrees[i]; i++) {
 		struct ref_store *refs;
 
 		if (worktrees[i]->is_detached)
diff --git a/builtin/bugreport.c b/builtin/bugreport.c
index 3106e56a13..cff8e1624b 100644
--- a/builtin/bugreport.c
+++ b/builtin/bugreport.c
@@ -47,15 +47,13 @@ static void get_system_info(struct strbuf *sys_info)
 
 static void get_populated_hooks(struct strbuf *hook_info, int nongit)
 {
-	const char **p;
-
 	if (nongit) {
 		strbuf_addstr(hook_info,
 			_("not run from a git repository - no hooks to show\n"));
 		return;
 	}
 
-	for (p = hook_name_list; *p; p++) {
+	for (const char **p = hook_name_list; *p; p++) {
 		const char *hook = *p;
 
 		if (hook_exists(hook))
diff --git a/builtin/cat-file.c b/builtin/cat-file.c
index bbf851138e..82b6d4f2c0 100644
--- a/builtin/cat-file.c
+++ b/builtin/cat-file.c
@@ -662,12 +662,10 @@ static void dispatch_calls(struct batch_options *opt,
 		struct queued_cmd *cmd,
 		int nr)
 {
-	int i;
-
 	if (!opt->buffer_output)
 		die(_("flush is only for --buffer mode"));
 
-	for (i = 0; i < nr; i++)
+	for (int i = 0; i < nr; i++)
 		cmd[i].fn(opt, cmd[i].line, output, data);
 
 	fflush(stdout);
@@ -675,9 +673,7 @@ static void dispatch_calls(struct batch_options *opt,
 
 static void free_cmds(struct queued_cmd *cmd, size_t *nr)
 {
-	size_t i;
-
-	for (i = 0; i < *nr; i++)
+	for (size_t i = 0; i < *nr; i++)
 		FREE_AND_NULL(cmd[i].line);
 
 	*nr = 0;
diff --git a/builtin/check-attr.c b/builtin/check-attr.c
index c1da1d184e..1ea30c0670 100644
--- a/builtin/check-attr.c
+++ b/builtin/check-attr.c
@@ -35,10 +35,9 @@ static const struct option check_attr_options[] = {
 
 static void output_attr(struct attr_check *check, const char *file)
 {
-	int j;
 	int cnt = check->nr;
 
-	for (j = 0; j < cnt; j++) {
+	for (int j = 0; j < cnt; j++) {
 		const char *value = check->items[j].value;
 
 		if (ATTR_TRUE(value))
diff --git a/builtin/check-ignore.c b/builtin/check-ignore.c
index 906cd96753..f146e3d254 100644
--- a/builtin/check-ignore.c
+++ b/builtin/check-ignore.c
@@ -75,7 +75,7 @@ static int check_ignore(struct dir_struct *dir,
 {
 	const char *full_path;
 	char *seen;
-	int num_ignored = 0, i;
+	int num_ignored = 0;
 	struct path_pattern *pattern;
 	struct pathspec pathspec;
 
@@ -104,7 +104,7 @@ static int check_ignore(struct dir_struct *dir,
 	 */
 	seen = find_pathspecs_matching_against_index(&pathspec, &the_index,
 						     PS_HEED_SKIP_WORKTREE);
-	for (i = 0; i < pathspec.nr; i++) {
+	for (int i = 0; i < pathspec.nr; i++) {
 		full_path = pathspec.items[i].match;
 		pattern = NULL;
 		if (!seen[i]) {
diff --git a/builtin/check-mailmap.c b/builtin/check-mailmap.c
index b8a05b8e07..294905528e 100644
--- a/builtin/check-mailmap.c
+++ b/builtin/check-mailmap.c
@@ -42,7 +42,6 @@ static void check_mailmap(struct string_list *mailmap, const char *contact)
 
 int cmd_check_mailmap(int argc, const char **argv, const char *prefix)
 {
-	int i;
 	struct string_list mailmap = STRING_LIST_INIT_NODUP;
 
 	git_config(git_default_config, NULL);
@@ -53,7 +52,7 @@ int cmd_check_mailmap(int argc, const char **argv, const char *prefix)
 
 	read_mailmap(&mailmap);
 
-	for (i = 0; i < argc; ++i)
+	for (int i = 0; i < argc; ++i)
 		check_mailmap(&mailmap, argv[i]);
 	maybe_flush_or_die(stdout, "stdout");
 
diff --git a/builtin/checkout--worker.c b/builtin/checkout--worker.c
index 6b62b5375b..44264dbbe2 100644
--- a/builtin/checkout--worker.c
+++ b/builtin/checkout--worker.c
@@ -81,7 +81,7 @@ static void release_pc_item_data(struct parallel_checkout_item *pc_item)
 static void worker_loop(struct checkout *state)
 {
 	struct parallel_checkout_item *items = NULL;
-	size_t i, nr = 0, alloc = 0;
+	size_t nr = 0, alloc = 0;
 
 	while (1) {
 		int len = packet_read(0, packet_buffer, sizeof(packet_buffer),
@@ -96,7 +96,7 @@ static void worker_loop(struct checkout *state)
 		packet_to_pc_item(packet_buffer, len, &items[nr++]);
 	}
 
-	for (i = 0; i < nr; i++) {
+	for (size_t i = 0; i < nr; i++) {
 		struct parallel_checkout_item *pc_item = &items[i];
 		write_pc_item(pc_item, state);
 		report_result(pc_item);
diff --git a/builtin/checkout-index.c b/builtin/checkout-index.c
index 2e086a204d..bb3ffc27ab 100644
--- a/builtin/checkout-index.c
+++ b/builtin/checkout-index.c
@@ -137,10 +137,10 @@ static int checkout_file(const char *name, const char *prefix)
 
 static int checkout_all(const char *prefix, int prefix_length)
 {
-	int i, errs = 0;
+	int errs = 0;
 	struct cache_entry *last_ce = NULL;
 
-	for (i = 0; i < the_index.cache_nr ; i++) {
+	for (int i = 0; i < the_index.cache_nr; i++) {
 		struct cache_entry *ce = the_index.cache[i];
 
 		if (S_ISSPARSEDIR(ce->ce_mode)) {
@@ -210,7 +210,6 @@ static int option_parse_stage(const struct option *opt,
 
 int cmd_checkout_index(int argc, const char **argv, const char *prefix)
 {
-	int i;
 	struct lock_file lock_file = LOCK_INIT;
 	int all = 0;
 	int read_from_stdin = 0;
@@ -290,7 +289,7 @@ int cmd_checkout_index(int argc, const char **argv, const char *prefix)
 		init_parallel_checkout();
 
 	/* Check out named files first */
-	for (i = 0; i < argc; i++) {
+	for (int i = 0; i < argc; i++) {
 		const char *arg = argv[i];
 		char *p;
 
diff --git a/builtin/checkout.c b/builtin/checkout.c
index 067c251933..1f5e2560a6 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -382,7 +382,6 @@ static int checkout_worktree(const struct checkout_opts *opts,
 	struct checkout state = CHECKOUT_INIT;
 	int nr_checkouts = 0, nr_unmerged = 0;
 	int errs = 0;
-	int pos;
 	int pc_workers, pc_threshold;
 	struct mem_pool ce_mem_pool;
 
@@ -401,7 +400,7 @@ static int checkout_worktree(const struct checkout_opts *opts,
 	if (pc_workers > 1)
 		init_parallel_checkout();
 
-	for (pos = 0; pos < the_index.cache_nr; pos++) {
+	for (int pos = 0; pos < the_index.cache_nr; pos++) {
 		struct cache_entry *ce = the_index.cache[pos];
 		if (ce->ce_flags & CE_MATCHED) {
 			if (!ce_stage(ce)) {
@@ -1290,7 +1289,6 @@ static int parse_branchname_arg(int argc, const char **argv,
 	const char *arg;
 	int dash_dash_pos;
 	int has_dash_dash = 0;
-	int i;
 
 	/*
 	 * case 1: git checkout <ref> -- [<paths>]
@@ -1344,7 +1342,7 @@ static int parse_branchname_arg(int argc, const char **argv,
 
 	arg = argv[0];
 	dash_dash_pos = -1;
-	for (i = 0; i < argc; i++) {
+	for (int i = 0; i < argc; i++) {
 		if (opts->accept_pathspec && !strcmp(argv[i], "--")) {
 			dash_dash_pos = i;
 			break;
diff --git a/builtin/clean.c b/builtin/clean.c
index d90766cad3..2e681f2e67 100644
--- a/builtin/clean.c
+++ b/builtin/clean.c
@@ -277,8 +277,7 @@ static int remove_dirs(struct strbuf *path, const char *prefix, int force_flag,
 	}
 
 	if (!*dir_gone && !quiet) {
-		int i;
-		for (i = 0; i < dels.nr; i++)
+		for (int i = 0; i < dels.nr; i++)
 			printf(dry_run ?  _(msg_would_remove) : _(msg_remove), dels.items[i].string);
 	}
 out:
@@ -408,7 +407,7 @@ static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
 {
 	struct menu_item *menu_item;
 	struct string_list_item *string_list_item;
-	int i, len, found = 0;
+	int len, found = 0;
 
 	len = strlen(choice);
 	switch (menu_stuff->type) {
@@ -417,7 +416,7 @@ static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
 	case MENU_STUFF_TYPE_MENU_ITEM:
 
 		menu_item = (struct menu_item *)menu_stuff->stuff;
-		for (i = 0; i < menu_stuff->nr; i++, menu_item++) {
+		for (int i = 0; i < menu_stuff->nr; i++, menu_item++) {
 			if (len == 1 && *choice == menu_item->hotkey) {
 				found = i + 1;
 				break;
@@ -439,7 +438,7 @@ static int find_unique(const char *choice, struct menu_stuff *menu_stuff)
 		break;
 	case MENU_STUFF_TYPE_STRING_LIST:
 		string_list_item = ((struct string_list *)menu_stuff->stuff)->items;
-		for (i = 0; i < menu_stuff->nr; i++, string_list_item++) {
+		for (int i = 0; i < menu_stuff->nr; i++, string_list_item++) {
 			if (!strncasecmp(choice, string_list_item->string, len)) {
 				if (found) {
 					found = 0;
@@ -479,7 +478,7 @@ static int parse_choice(struct menu_stuff *menu_stuff,
 			struct strbuf input,
 			int **chosen)
 {
-	struct strbuf **choice_list, **ptr;
+	struct strbuf **choice_list;
 	int nr = 0;
 	int i;
 
@@ -494,7 +493,7 @@ static int parse_choice(struct menu_stuff *menu_stuff,
 		choice_list = strbuf_split_max(&input, ' ', 0);
 	}
 
-	for (ptr = choice_list; *ptr; ptr++) {
+	for (struct strbuf **ptr = choice_list; *ptr; ptr++) {
 		char *p;
 		int choose = 1;
 		int bottom = 0, top = 0;
@@ -886,9 +885,9 @@ static void interactive_main_loop(void)
 
 static void correct_untracked_entries(struct dir_struct *dir)
 {
-	int src, dst, ign;
+	int dst, ign;
 
-	for (src = dst = ign = 0; src < dir->nr; src++) {
+	for (int src = dst = ign = 0; src < dir->nr; src++) {
 		/* skip paths in ignored[] that cannot be inside entries[src] */
 		while (ign < dir->ignored_nr &&
 		       0 <= cmp_dir_entry(&dir->entries[src], &dir->ignored[ign]))
diff --git a/builtin/clone.c b/builtin/clone.c
index bad1b70ce8..a1abcbdf31 100644
--- a/builtin/clone.c
+++ b/builtin/clone.c
@@ -511,8 +511,7 @@ static struct ref *wanted_peer_refs(const struct ref *refs,
 			warning(_("Could not find remote branch %s to clone."),
 				option_branch);
 		else {
-			int i;
-			for (i = 0; i < refspec->nr; i++)
+			for (int i = 0; i < refspec->nr; i++)
 				get_fetch_map(remote_head, &refspec->items[i],
 					      &tail, 0);
 
@@ -521,8 +520,7 @@ static struct ref *wanted_peer_refs(const struct ref *refs,
 		}
 		free_refs(remote_head);
 	} else {
-		int i;
-		for (i = 0; i < refspec->nr; i++)
+		for (int i = 0; i < refspec->nr; i++)
 			get_fetch_map(refs, &refspec->items[i], &tail, 0);
 	}
 
@@ -534,8 +532,6 @@ static struct ref *wanted_peer_refs(const struct ref *refs,
 
 static void write_remote_refs(const struct ref *local_refs)
 {
-	const struct ref *r;
-
 	struct ref_transaction *t;
 	struct strbuf err = STRBUF_INIT;
 
@@ -543,7 +539,7 @@ static void write_remote_refs(const struct ref *local_refs)
 	if (!t)
 		die("%s", err.buf);
 
-	for (r = local_refs; r; r = r->next) {
+	for (const struct ref *r = local_refs; r; r = r->next) {
 		if (!r->peer_ref)
 			continue;
 		if (ref_transaction_create(t, r->peer_ref->name, &r->old_oid,
@@ -560,8 +556,7 @@ static void write_remote_refs(const struct ref *local_refs)
 
 static void write_followtags(const struct ref *refs, const char *msg)
 {
-	const struct ref *ref;
-	for (ref = refs; ref; ref = ref->next) {
+	for (const struct ref *ref = refs; ref; ref = ref->next) {
 		if (!starts_with(ref->name, "refs/tags/"))
 			continue;
 		if (ends_with(ref->name, "^{}"))
@@ -826,9 +821,7 @@ static int write_one_config(const char *key, const char *value,
 
 static void write_config(struct string_list *config)
 {
-	int i;
-
-	for (i = 0; i < config->nr; i++) {
+	for (int i = 0; i < config->nr; i++) {
 		if (git_config_parse_parameter(config->items[i].string,
 					       write_one_config, NULL) < 0)
 			die(_("unable to write parameters to config file"));
diff --git a/builtin/commit-tree.c b/builtin/commit-tree.c
index 1bb7819839..4dacdefa2f 100644
--- a/builtin/commit-tree.c
+++ b/builtin/commit-tree.c
@@ -25,8 +25,7 @@ static const char *sign_commit;
 static void new_parent(struct commit *parent, struct commit_list **parents_p)
 {
 	struct object_id *oid = &parent->object.oid;
-	struct commit_list *parents;
-	for (parents = *parents_p; parents; parents = parents->next) {
+	for (struct commit_list *parents = *parents_p; parents; parents = parents->next) {
 		if (parents->item == parent) {
 			error(_("duplicate parent %s ignored"), oid_to_hex(oid));
 			return;
diff --git a/builtin/commit.c b/builtin/commit.c
index 6d1fa71676..1782909eef 100644
--- a/builtin/commit.c
+++ b/builtin/commit.c
@@ -256,7 +256,7 @@ static int commit_index_files(void)
 static int list_paths(struct string_list *list, const char *with_tree,
 		      const struct pathspec *pattern)
 {
-	int i, ret;
+	int ret;
 	char *m;
 
 	if (!pattern->nr)
@@ -272,7 +272,7 @@ static int list_paths(struct string_list *list, const char *with_tree,
 
 	/* TODO: audit for interaction with sparse-index. */
 	ensure_full_index(&the_index);
-	for (i = 0; i < the_index.cache_nr; i++) {
+	for (int i = 0; i < the_index.cache_nr; i++) {
 		const struct cache_entry *ce = the_index.cache[i];
 		struct string_list_item *item;
 
@@ -292,8 +292,7 @@ static int list_paths(struct string_list *list, const char *with_tree,
 
 static void add_remove_files(struct string_list *list)
 {
-	int i;
-	for (i = 0; i < list->nr; i++) {
+	for (int i = 0; i < list->nr; i++) {
 		struct stat st;
 		struct string_list_item *p = &(list->items[i]);
 
@@ -1001,11 +1000,11 @@ static int prepare_to_commit(const char *index_file, const char *prefix,
 			parent = "HEAD^1";
 
 		if (repo_get_oid(the_repository, parent, &oid)) {
-			int i, ita_nr = 0;
+			int ita_nr = 0;
 
 			/* TODO: audit for interaction with sparse-index. */
 			ensure_full_index(&the_index);
-			for (i = 0; i < the_index.cache_nr; i++)
+			for (int i = 0; i < the_index.cache_nr; i++)
 				if (ce_intent_to_add(the_index.cache[i]))
 					ita_nr++;
 			committable = the_index.cache_nr - ita_nr > 0;
diff --git a/builtin/config.c b/builtin/config.c
index b55bfae7d6..10a181daec 100644
--- a/builtin/config.c
+++ b/builtin/config.c
@@ -333,7 +333,6 @@ static int get_value(const char *key_, const char *regex_, unsigned flags)
 {
 	int ret = CONFIG_GENERIC_ERROR;
 	struct strbuf_list values = {NULL};
-	int i;
 
 	if (use_key_regexp) {
 		char *tl;
@@ -402,7 +401,7 @@ static int get_value(const char *key_, const char *regex_, unsigned flags)
 
 	ret = !values.nr;
 
-	for (i = 0; i < values.nr; i++) {
+	for (int i = 0; i < values.nr; i++) {
 		struct strbuf *buf = values.items + i;
 		if (do_all || i == values.nr - 1)
 			fwrite(buf->buf, 1, buf->len, stdout);
diff --git a/builtin/count-objects.c b/builtin/count-objects.c
index 2d4bb5e8d0..5e8731d3f4 100644
--- a/builtin/count-objects.c
+++ b/builtin/count-objects.c
@@ -120,14 +120,13 @@ int cmd_count_objects(int argc, const char **argv, const char *prefix)
 				      count_loose, count_cruft, NULL, NULL);
 
 	if (verbose) {
-		struct packed_git *p;
 		unsigned long num_pack = 0;
 		off_t size_pack = 0;
 		struct strbuf loose_buf = STRBUF_INIT;
 		struct strbuf pack_buf = STRBUF_INIT;
 		struct strbuf garbage_buf = STRBUF_INIT;
 
-		for (p = get_all_packs(the_repository); p; p = p->next) {
+		for (struct packed_git *p = get_all_packs(the_repository); p; p = p->next) {
 			if (!p->pack_local)
 				continue;
 			if (open_pack_index(p))
diff --git a/builtin/credential-cache--daemon.c b/builtin/credential-cache--daemon.c
index 3a6a750a8e..09a30ceafc 100644
--- a/builtin/credential-cache--daemon.c
+++ b/builtin/credential-cache--daemon.c
@@ -34,8 +34,7 @@ static void cache_credential(struct credential *c, int timeout)
 
 static struct credential_cache_entry *lookup_credential(const struct credential *c)
 {
-	int i;
-	for (i = 0; i < entries_nr; i++) {
+	for (int i = 0; i < entries_nr; i++) {
 		struct credential *e = &entries[i].item;
 		if (credential_match(c, e, 0))
 			return &entries[i];
@@ -45,10 +44,7 @@ static struct credential_cache_entry *lookup_credential(const struct credential
 
 static void remove_credential(const struct credential *c, int match_password)
 {
-	struct credential_cache_entry *e;
-
-	int i;
-	for (i = 0; i < entries_nr; i++) {
+	struct credential_cache_entry *e;for (int i = 0; i < entries_nr; i++) {
 		e = &entries[i];
 		if (credential_match(c, &e->item, match_password))
 			e->expiration = 0;
diff --git a/builtin/describe.c b/builtin/describe.c
index d6c77a714f..59b22e27c3 100644
--- a/builtin/describe.c
+++ b/builtin/describe.c
@@ -450,8 +450,8 @@ static void describe_commit(struct object_id *oid, struct strbuf *dst)
 	if (debug) {
 		static int label_width = -1;
 		if (label_width < 0) {
-			int i, w;
-			for (i = 0; i < ARRAY_SIZE(prio_names); i++) {
+			int w;
+			for (int i = 0; i < ARRAY_SIZE(prio_names); i++) {
 				w = strlen(_(prio_names[i]));
 				if (label_width < w)
 					label_width = w;
diff --git a/builtin/diff-index.c b/builtin/diff-index.c
index 3e05260ac0..2b47986df4 100644
--- a/builtin/diff-index.c
+++ b/builtin/diff-index.c
@@ -18,7 +18,6 @@ int cmd_diff_index(int argc, const char **argv, const char *prefix)
 {
 	struct rev_info rev;
 	unsigned int option = 0;
-	int i;
 	int result;
 
 	if (argc == 2 && !strcmp(argv[1], "-h"))
@@ -36,7 +35,7 @@ int cmd_diff_index(int argc, const char **argv, const char *prefix)
 	diff_merges_suppress_m_parsing();
 
 	argc = setup_revisions(argc, argv, &rev, NULL);
-	for (i = 1; i < argc; i++) {
+	for (int i = 1; i < argc; i++) {
 		const char *arg = argv[i];
 
 		if (!strcmp(arg, "--cached"))
diff --git a/builtin/diff.c b/builtin/diff.c
index 6e196e0c7d..f9779a4c8d 100644
--- a/builtin/diff.c
+++ b/builtin/diff.c
@@ -211,7 +211,6 @@ static void builtin_diff_combined(struct rev_info *revs,
 				  int ents, int first_non_parent)
 {
 	struct oid_array parents = OID_ARRAY_INIT;
-	int i;
 
 	if (argc > 1)
 		usage(builtin_diff_usage);
@@ -223,7 +222,7 @@ static void builtin_diff_combined(struct rev_info *revs,
 
 	diff_merges_set_dense_combined_if_unset(revs);
 
-	for (i = 0; i < ents; i++) {
+	for (int i = 0; i < ents; i++) {
 		if (i != first_non_parent)
 			oid_array_append(&parents, &ent[i].item->oid);
 	}
@@ -313,7 +312,7 @@ struct symdiff {
  */
 static void symdiff_prepare(struct rev_info *rev, struct symdiff *sym)
 {
-	int i, is_symdiff = 0, basecount = 0, othercount = 0;
+	int is_symdiff = 0, basecount = 0, othercount = 0;
 	int lpos = -1, rpos = -1, basepos = -1;
 	struct bitmap *map = NULL;
 
@@ -332,7 +331,7 @@ static void symdiff_prepare(struct rev_info *rev, struct symdiff *sym)
 	 * so we must check for SYMMETRIC_LEFT too.  The two arrays
 	 * rev->pending.objects and rev->cmdline.rev are parallel.
 	 */
-	for (i = 0; i < rev->cmdline.nr; i++) {
+	for (int i = 0; i < rev->cmdline.nr; i++) {
 		struct object *obj = rev->pending.objects[i].item;
 		switch (rev->cmdline.rev[i].whence) {
 		case REV_CMD_MERGE_BASE:
diff --git a/builtin/fast-export.c b/builtin/fast-export.c
index 4693d18cc9..6cebf8f4ab 100644
--- a/builtin/fast-export.c
+++ b/builtin/fast-export.c
@@ -430,7 +430,6 @@ static const char *anonymize_oid(const char *oid_hex)
 static void show_filemodify(struct diff_queue_struct *q,
 			    struct diff_options *options UNUSED, void *data)
 {
-	int i;
 	struct string_list *changed = data;
 
 	/*
@@ -439,7 +438,7 @@ static void show_filemodify(struct diff_queue_struct *q,
 	 */
 	QSORT(q->queue, q->nr, depth_first);
 
-	for (i = 0; i < q->nr; i++) {
+	for (int i = 0; i < q->nr; i++) {
 		struct diff_filespec *ospec = q->queue[i]->one;
 		struct diff_filespec *spec = q->queue[i]->two;
 
@@ -543,10 +542,9 @@ static const char *anonymize_refname(const char *refname)
 	};
 	static struct hashmap refs;
 	static struct strbuf anon = STRBUF_INIT;
-	int i;
 
 	strbuf_reset(&anon);
-	for (i = 0; i < ARRAY_SIZE(prefixes); i++) {
+	for (int i = 0; i < ARRAY_SIZE(prefixes); i++) {
 		if (skip_prefix(refname, prefixes[i], &refname)) {
 			strbuf_addstr(&anon, prefixes[i]);
 			break;
@@ -926,9 +924,7 @@ static struct commit *get_commit(struct rev_cmdline_entry *e, char *full_name)
 
 static void get_tags_and_duplicates(struct rev_cmdline_info *info)
 {
-	int i;
-
-	for (i = 0; i < info->nr; i++) {
+	for (int i = 0; i < info->nr; i++) {
 		struct rev_cmdline_entry *e = info->rev + i;
 		struct object_id oid;
 		struct commit *commit;
@@ -988,9 +984,7 @@ static void get_tags_and_duplicates(struct rev_cmdline_info *info)
 static void handle_tags_and_duplicates(struct string_list *extras)
 {
 	struct commit *commit;
-	int i;
-
-	for (i = extras->nr - 1; i >= 0; i--) {
+	for (int i = extras->nr - 1; i >= 0; i--) {
 		const char *name = extras->items[i].string;
 		struct object *object = extras->items[i].util;
 		int mark;
@@ -1050,7 +1044,6 @@ static void handle_tags_and_duplicates(struct string_list *extras)
 
 static void export_marks(char *file)
 {
-	unsigned int i;
 	uint32_t mark;
 	struct decoration_entry *deco = idnums.entries;
 	FILE *f;
@@ -1060,7 +1053,7 @@ static void export_marks(char *file)
 	if (!f)
 		die_errno("Unable to open marks file %s for writing.", file);
 
-	for (i = 0; i < idnums.size; i++) {
+	for (unsigned int i = 0; i < idnums.size; i++) {
 		if (deco->base && deco->base->type == 1) {
 			mark = ptr_to_mark(deco->decoration);
 			if (fprintf(f, ":%"PRIu32" %s\n", mark,
@@ -1135,8 +1128,7 @@ static void import_marks(char *input_file, int check_exists)
 
 static void handle_deletes(void)
 {
-	int i;
-	for (i = 0; i < refspecs.nr; i++) {
+	for (int i = 0; i < refspecs.nr; i++) {
 		struct refspec_item *refspec = &refspecs.items[i];
 		if (*refspec->src)
 			continue;
@@ -1247,9 +1239,7 @@ int cmd_fast_export(int argc, const char **argv, const char *prefix)
 		die(_("the option '%s' requires '%s'"), "--anonymize-map", "--anonymize");
 
 	if (refspecs_list.nr) {
-		int i;
-
-		for (i = 0; i < refspecs_list.nr; i++)
+		for (int i = 0; i < refspecs_list.nr; i++)
 			refspec_append(&refspecs, refspecs_list.items[i].string);
 
 		string_list_clear(&refspecs_list, 1);
diff --git a/builtin/fast-import.c b/builtin/fast-import.c
index 92eda20683..4fd4b9284a 100644
--- a/builtin/fast-import.c
+++ b/builtin/fast-import.c
@@ -273,14 +273,13 @@ static void parse_ls(const char *p, struct branch *b);
 
 static void for_each_mark(struct mark_set *m, uintmax_t base, each_mark_fn_t callback, void *p)
 {
-	uintmax_t k;
 	if (m->shift) {
-		for (k = 0; k < 1024; k++) {
+		for (uintmax_t k = 0; k < 1024; k++) {
 			if (m->data.sets[k])
 				for_each_mark(m->data.sets[k], base + (k << m->shift), callback, p);
 		}
 	} else {
-		for (k = 0; k < 1024; k++) {
+		for (uintmax_t k = 0; k < 1024; k++) {
 			if (m->data.marked[k])
 				callback(base + k, m->data.marked[k], p);
 		}
@@ -328,7 +327,6 @@ static void write_crash_report(const char *err)
 	FILE *rpt = fopen(loc, "w");
 	struct branch *b;
 	unsigned long lu;
-	struct recent_command *rc;
 
 	if (!rpt) {
 		error_errno("can't write crash report %s", loc);
@@ -351,7 +349,7 @@ static void write_crash_report(const char *err)
 	fputc('\n', rpt);
 	fputs("Most Recent Commands Before Crash\n", rpt);
 	fputs("---------------------------------\n", rpt);
-	for (rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
+	for (struct recent_command *rc = cmd_hist.next; rc != &cmd_hist; rc = rc->next) {
 		if (rc->next == &cmd_hist)
 			fputs("* ", rpt);
 		else
@@ -382,11 +380,10 @@ static void write_crash_report(const char *err)
 	}
 
 	if (first_tag) {
-		struct tag *tg;
 		fputc('\n', rpt);
 		fputs("Annotated Tags\n", rpt);
 		fputs("--------------\n", rpt);
-		for (tg = first_tag; tg; tg = tg->next_tag) {
+		for (struct tag *tg = first_tag; tg; tg = tg->next_tag) {
 			fputs(oid_to_hex(&tg->oid), rpt);
 			fputc(' ', rpt);
 			fputs(tg->name, rpt);
@@ -511,8 +508,6 @@ static struct object_entry *insert_object(struct object_id *oid)
 
 static void invalidate_pack_id(unsigned int id)
 {
-	unsigned long lu;
-	struct tag *t;
 	struct hashmap_iter iter;
 	struct object_entry *e;
 
@@ -521,7 +516,7 @@ static void invalidate_pack_id(unsigned int id)
 			e->pack_id = MAX_PACK_ID;
 	}
 
-	for (lu = 0; lu < branch_table_sz; lu++) {
+	for (unsigned long lu = 0; lu < branch_table_sz; lu++) {
 		struct branch *b;
 
 		for (b = branch_table[lu]; b; b = b->table_next_branch)
@@ -529,7 +524,7 @@ static void invalidate_pack_id(unsigned int id)
 				b->pack_id = MAX_PACK_ID;
 	}
 
-	for (t = first_tag; t; t = t->next_tag)
+	for (struct tag *t = first_tag; t; t = t->next_tag)
 		if (t->pack_id == id)
 			t->pack_id = MAX_PACK_ID;
 }
@@ -606,9 +601,7 @@ static struct atom_str *to_atom(const char *s, unsigned short len)
 static struct branch *lookup_branch(const char *name)
 {
 	unsigned int hc = hc_str(name, strlen(name)) % branch_table_sz;
-	struct branch *b;
-
-	for (b = branch_table[hc]; b; b = b->table_next_branch)
+	for (struct branch *b = branch_table[hc]; b; b = b->table_next_branch)
 		if (!strcmp(name, b->name))
 			return b;
 	return NULL;
@@ -681,8 +674,7 @@ static void release_tree_content(struct tree_content *t)
 
 static void release_tree_content_recursive(struct tree_content *t)
 {
-	unsigned int i;
-	for (i = 0; i < t->entry_count; i++)
+	for (unsigned int i = 0; i < t->entry_count; i++)
 		release_tree_entry(t->entries[i]);
 	release_tree_content(t);
 }
@@ -732,12 +724,11 @@ static struct tree_content *dup_tree_content(struct tree_content *s)
 {
 	struct tree_content *d;
 	struct tree_entry *a, *b;
-	unsigned int i;
 
 	if (!s)
 		return NULL;
 	d = new_tree_content(s->entry_count);
-	for (i = 0; i < s->entry_count; i++) {
+	for (unsigned int i = 0; i < s->entry_count; i++) {
 		a = s->entries[i];
 		b = new_tree_entry();
 		memcpy(b, a, sizeof(*a));
@@ -780,12 +771,11 @@ static const char *create_index(void)
 	const char *tmpfile;
 	struct pack_idx_entry **idx, **c, **last;
 	struct object_entry *e;
-	struct object_entry_pool *o;
 
 	/* Build the table of object IDs. */
 	ALLOC_ARRAY(idx, object_count);
 	c = idx;
-	for (o = blocks; o; o = o->next_pool)
+	for (struct object_entry_pool *o = blocks; o; o = o->next_pool)
 		for (e = o->next_free; e-- != o->entries;)
 			if (pack_id == e->pack_id)
 				*c++ = &e->idx;
@@ -827,9 +817,7 @@ static char *keep_pack(const char *curr_index_name)
 static void unkeep_all_packs(void)
 {
 	struct strbuf name = STRBUF_INIT;
-	int k;
-
-	for (k = 0; k < pack_id; k++) {
+	for (int k = 0; k < pack_id; k++) {
 		struct packed_git *p = all_packs[k];
 		odb_pack_name(&name, p->hash, "keep");
 		unlink_or_warn(name.buf);
@@ -1416,7 +1404,7 @@ static int tree_content_set(
 {
 	struct tree_content *t;
 	const char *slash1;
-	unsigned int i, n;
+	unsigned int n;
 	struct tree_entry *e;
 
 	slash1 = strchrnul(p, '/');
@@ -1429,7 +1417,7 @@ static int tree_content_set(
 	if (!root->tree)
 		load_tree(root);
 	t = root->tree;
-	for (i = 0; i < t->entry_count; i++) {
+	for (unsigned int i = 0; i < t->entry_count; i++) {
 		e = t->entries[i];
 		if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
 			if (!*slash1) {
@@ -1504,7 +1492,7 @@ static int tree_content_remove(
 {
 	struct tree_content *t;
 	const char *slash1;
-	unsigned int i, n;
+	unsigned int n;
 	struct tree_entry *e;
 
 	slash1 = strchrnul(p, '/');
@@ -1519,7 +1507,7 @@ static int tree_content_remove(
 	}
 
 	t = root->tree;
-	for (i = 0; i < t->entry_count; i++) {
+	for (unsigned int i = 0; i < t->entry_count; i++) {
 		e = t->entries[i];
 		if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
 			if (*slash1 && !S_ISDIR(e->versions[1].mode))
@@ -1569,7 +1557,7 @@ static int tree_content_get(
 {
 	struct tree_content *t;
 	const char *slash1;
-	unsigned int i, n;
+	unsigned int n;
 	struct tree_entry *e;
 
 	slash1 = strchrnul(p, '/');
@@ -1586,7 +1574,7 @@ static int tree_content_get(
 	}
 
 	t = root->tree;
-	for (i = 0; i < t->entry_count; i++) {
+	for (unsigned int i = 0; i < t->entry_count; i++) {
 		e = t->entries[i];
 		if (e->name->str_len == n && !fspathncmp(p, e->name->str_dat, n)) {
 			if (!*slash1)
@@ -1658,10 +1646,9 @@ static int update_branch(struct branch *b)
 
 static void dump_branches(void)
 {
-	unsigned int i;
 	struct branch *b;
 
-	for (i = 0; i < branch_table_sz; i++) {
+	for (unsigned int i = 0; i < branch_table_sz; i++) {
 		for (b = branch_table[i]; b; b = b->table_next_branch)
 			failure |= update_branch(b);
 	}
@@ -1670,7 +1657,6 @@ static void dump_branches(void)
 static void dump_tags(void)
 {
 	static const char *msg = "fast-import";
-	struct tag *t;
 	struct strbuf ref_name = STRBUF_INIT;
 	struct strbuf err = STRBUF_INIT;
 	struct ref_transaction *transaction;
@@ -1680,7 +1666,7 @@ static void dump_tags(void)
 		failure |= error("%s", err.buf);
 		goto cleanup;
 	}
-	for (t = first_tag; t; t = t->next_tag) {
+	for (struct tag *t = first_tag; t; t = t->next_tag) {
 		strbuf_reset(&ref_name);
 		strbuf_addf(&ref_name, "refs/tags/%s", t->name);
 
@@ -2105,7 +2091,7 @@ static uintmax_t do_change_note_fanout(
 {
 	struct tree_content *t;
 	struct tree_entry *e, leaf;
-	unsigned int i, tmp_hex_oid_len, tmp_fullpath_len;
+	unsigned int tmp_hex_oid_len, tmp_fullpath_len;
 	uintmax_t num_notes = 0;
 	struct object_id oid;
 	/* hex oid + '/' between each pair of hex digits + NUL */
@@ -2116,7 +2102,7 @@ static uintmax_t do_change_note_fanout(
 		load_tree(root);
 	t = root->tree;
 
-	for (i = 0; t && i < t->entry_count; i++) {
+	for (unsigned int i = 0; t && i < t->entry_count; i++) {
 		e = t->entries[i];
 		tmp_hex_oid_len = hex_oid_len + e->name->str_len;
 		tmp_fullpath_len = fullpath_len;
diff --git a/builtin/fetch-pack.c b/builtin/fetch-pack.c
index 44c05ee86c..577d2d0db9 100644
--- a/builtin/fetch-pack.c
+++ b/builtin/fetch-pack.c
@@ -242,11 +242,9 @@ int cmd_fetch_pack(int argc, const char **argv, const char *prefix UNUSED)
 	ref = fetch_pack(&args, fd, ref, sought, nr_sought,
 			 &shallow, pack_lockfiles_ptr, version);
 	if (pack_lockfiles.nr) {
-		int i;
-
 		printf("lock %s\n", pack_lockfiles.items[0].string);
 		fflush(stdout);
-		for (i = 1; i < pack_lockfiles.nr; i++)
+		for (int i = 1; i < pack_lockfiles.nr; i++)
 			warning(_("Lockfile created but not reported: %s"),
 				pack_lockfiles.items[i].string);
 	}
diff --git a/builtin/fetch.c b/builtin/fetch.c
index 3aedfd1bb6..08ebb55d0d 100644
--- a/builtin/fetch.c
+++ b/builtin/fetch.c
@@ -210,9 +210,7 @@ static void add_merge_config(struct ref **head,
 		           struct branch *branch,
 		           struct ref ***tail)
 {
-	int i;
-
-	for (i = 0; i < branch->merge_nr; i++) {
+	for (int i = 0; i < branch->merge_nr; i++) {
 		struct ref *rm, **old_tail = *tail;
 		struct refspec_item refspec;
 
@@ -331,7 +329,6 @@ static void find_non_local_tags(const struct ref *refs,
 	struct oidset fetch_oids = OIDSET_INIT;
 	struct string_list remote_refs_list = STRING_LIST_INIT_NODUP;
 	struct string_list_item *remote_ref_item;
-	const struct ref *ref;
 	struct refname_hash_entry *item = NULL;
 	const int quick_flags = OBJECT_INFO_QUICK | OBJECT_INFO_SKIP_FETCH_OBJECT;
 
@@ -350,7 +347,7 @@ static void find_non_local_tags(const struct ref *refs,
 						       add_already_queued_tags,
 						       &existing_refs);
 
-	for (ref = refs; ref; ref = ref->next) {
+	for (const struct ref *ref = refs; ref; ref = ref->next) {
 		if (!starts_with(ref->name, "refs/tags/"))
 			continue;
 
@@ -434,12 +431,10 @@ static void find_non_local_tags(const struct ref *refs,
 
 static void filter_prefetch_refspec(struct refspec *rs)
 {
-	int i;
-
 	if (!prefetch)
 		return;
 
-	for (i = 0; i < rs->nr; i++) {
+	for (int i = 0; i < rs->nr; i++) {
 		struct strbuf new_dst = STRBUF_INIT;
 		char *old_dst;
 		const char *sub = NULL;
@@ -698,14 +693,13 @@ static int s_update_ref(const char *action,
 
 static int refcol_width(const struct ref *ref_map, int compact_format)
 {
-	const struct ref *ref;
 	int max, width = 10;
 
 	max = term_columns();
 	if (compact_format)
 		max = max * 2 / 3;
 
-	for (ref = ref_map; ref; ref = ref->next) {
+	for (const struct ref *ref = ref_map; ref; ref = ref->next) {
 		int rlen, llen = 0, len;
 
 		if (ref->status == REF_STATUS_REJECT_SHALLOW ||
@@ -1138,7 +1132,6 @@ static int store_updated_refs(struct display_state *display_state,
 	struct strbuf note = STRBUF_INIT;
 	const char *what, *kind;
 	struct ref *rm;
-	int want_status;
 	int summary_width = 0;
 
 	if (verbosity >= 0)
@@ -1161,9 +1154,7 @@ static int store_updated_refs(struct display_state *display_state,
 	 * merged entries are written before not-for-merge. That lets readers
 	 * use FETCH_HEAD as a refname to refer to the ref to be merged.
 	 */
-	for (want_status = FETCH_HEAD_MERGE;
-	     want_status <= FETCH_HEAD_IGNORE;
-	     want_status++) {
+	for (int want_status = FETCH_HEAD_MERGE; want_status <= FETCH_HEAD_IGNORE; want_status++) {
 		for (rm = ref_map; rm; rm = rm->next) {
 			struct ref *ref = NULL;
 
@@ -1294,7 +1285,6 @@ static int check_exist_and_connected(struct ref *ref_map)
 {
 	struct ref *rm = ref_map;
 	struct check_connected_options opt = CHECK_CONNECTED_INIT;
-	struct ref *r;
 
 	/*
 	 * If we are deepening a shallow clone we already have these
@@ -1318,7 +1308,7 @@ static int check_exist_and_connected(struct ref *ref_map)
 	 * check_connected() allows objects to merely be promised, but
 	 * we need all direct targets to exist.
 	 */
-	for (r = rm; r; r = r->next) {
+	for (struct ref *r = rm; r; r = r->next) {
 		if (!repo_has_object_file_with_flags(the_repository, &r->old_oid,
 						     OBJECT_INFO_SKIP_FETCH_OBJECT))
 			return -1;
@@ -1462,9 +1452,7 @@ static int add_oid(const char *refname UNUSED,
 static void add_negotiation_tips(struct git_transport_options *smart_options)
 {
 	struct oid_array *oids = xcalloc(1, sizeof(*oids));
-	int i;
-
-	for (i = 0; i < negotiation_tip.nr; i++) {
+	for (int i = 0; i < negotiation_tip.nr; i++) {
 		const char *s = negotiation_tip.items[i].string;
 		int old_nr;
 		if (!has_glob_specials(s)) {
@@ -1592,8 +1580,6 @@ static int do_fetch(struct transport *transport,
 	}
 
 	if (rs->nr) {
-		int i;
-
 		refspec_ref_prefixes(rs, &transport_ls_refs_options.ref_prefixes);
 
 		/*
@@ -1601,7 +1587,7 @@ static int do_fetch(struct transport *transport,
 		 * OIDs
 		 */
 		must_list_refs = 0;
-		for (i = 0; i < rs->nr; i++) {
+		for (int i = 0; i < rs->nr; i++) {
 			if (!rs->items[i].exact_sha1) {
 				must_list_refs = 1;
 				break;
@@ -1615,8 +1601,7 @@ static int do_fetch(struct transport *transport,
 					     &transport_ls_refs_options.ref_prefixes);
 		if (branch_has_merge_config(branch) &&
 		    !strcmp(branch->remote_name, transport->remote->name)) {
-			int i;
-			for (i = 0; i < branch->merge_nr; i++) {
+			for (int i = 0; i < branch->merge_nr; i++) {
 				strvec_push(&transport_ls_refs_options.ref_prefixes,
 					    branch->merge[i]->src);
 			}
@@ -1725,7 +1710,6 @@ static int do_fetch(struct transport *transport,
 
 	if (set_upstream) {
 		struct branch *branch = branch_get("HEAD");
-		struct ref *rm;
 		struct ref *source_ref = NULL;
 
 		/*
@@ -1738,7 +1722,7 @@ static int do_fetch(struct transport *transport,
 		 * request ambiguous and err on the safe side by doing
 		 * nothing and just emit a warning.
 		 */
-		for (rm = ref_map; rm; rm = rm->next) {
+		for (struct ref *rm = ref_map; rm; rm = rm->next) {
 			if (!rm->peer_ref) {
 				if (source_ref) {
 					warning(_("multiple branches detected, incompatible with --set-upstream"));
@@ -2049,7 +2033,6 @@ static int fetch_one(struct remote *remote, int argc, const char **argv,
 		     const struct fetch_config *config)
 {
 	struct refspec rs = REFSPEC_INIT_FETCH;
-	int i;
 	int exit_code;
 	int maybe_prune_tags;
 	int remote_via_config = remote_is_configured(remote, 0);
@@ -2087,7 +2070,7 @@ static int fetch_one(struct remote *remote, int argc, const char **argv,
 	if (maybe_prune_tags && (argc || !remote_via_config))
 		refspec_append(&rs, TAG_REFSPEC);
 
-	for (i = 0; i < argc; i++) {
+	for (int i = 0; i < argc; i++) {
 		if (!strcmp(argv[i], "tag")) {
 			i++;
 			if (i >= argc)
diff --git a/builtin/for-each-repo.c b/builtin/for-each-repo.c
index 28186b30f5..4fc94e2b2c 100644
--- a/builtin/for-each-repo.c
+++ b/builtin/for-each-repo.c
@@ -14,14 +14,13 @@ static const char * const for_each_repo_usage[] = {
 
 static int run_command_on_repo(const char *path, int argc, const char ** argv)
 {
-	int i;
 	struct child_process child = CHILD_PROCESS_INIT;
 	char *abspath = interpolate_path(path, 0);
 
 	child.git_cmd = 1;
 	strvec_pushl(&child.args, "-C", abspath, NULL);
 
-	for (i = 0; i < argc; i++)
+	for (int i = 0; i < argc; i++)
 		strvec_push(&child.args, argv[i]);
 
 	free(abspath);
@@ -32,7 +31,7 @@ static int run_command_on_repo(const char *path, int argc, const char ** argv)
 int cmd_for_each_repo(int argc, const char **argv, const char *prefix)
 {
 	static const char *config_key = NULL;
-	int i, result = 0;
+	int result = 0;
 	const struct string_list *values;
 	int err;
 
@@ -55,7 +54,7 @@ int cmd_for_each_repo(int argc, const char **argv, const char *prefix)
 	else if (err)
 		return 0;
 
-	for (i = 0; !result && i < values->nr; i++)
+	for (int i = 0; !result && i < values->nr; i++)
 		result = run_command_on_repo(values->items[i].string, argc, argv);
 
 	return result;
diff --git a/builtin/fsck.c b/builtin/fsck.c
index a7cf94f67e..52084409d6 100644
--- a/builtin/fsck.c
+++ b/builtin/fsck.c
@@ -366,7 +366,7 @@ static void check_object(struct object *obj)
 
 static void check_connectivity(void)
 {
-	int i, max;
+	int max;
 
 	/* Traverse the pending reachable objects */
 	traverse_reachable();
@@ -396,7 +396,7 @@ static void check_connectivity(void)
 	if (verbose)
 		fprintf_ln(stderr, _("Checking connectivity (%d objects)"), max);
 
-	for (i = 0; i < max; i++) {
+	for (int i = 0; i < max; i++) {
 		struct object *obj = get_indexed_object(i);
 
 		if (obj)
@@ -561,14 +561,14 @@ static int fsck_head_link(const char *head_ref_name,
 
 static void get_default_heads(void)
 {
-	struct worktree **worktrees, **p;
+	struct worktree **worktrees;
 	const char *head_points_at;
 	struct object_id head_oid;
 
 	for_each_rawref(fsck_handle_ref, NULL);
 
 	worktrees = get_worktrees();
-	for (p = worktrees; *p; p++) {
+	for (struct worktree **p = worktrees; *p; p++) {
 		struct worktree *wt = *p;
 		struct strbuf ref = STRBUF_INIT;
 
@@ -742,7 +742,6 @@ static int fsck_head_link(const char *head_ref_name,
 
 static int fsck_cache_tree(struct cache_tree *it, const char *index_path)
 {
-	int i;
 	int err = 0;
 
 	if (verbose)
@@ -762,7 +761,7 @@ static int fsck_cache_tree(struct cache_tree *it, const char *index_path)
 		if (obj->type != OBJ_TREE)
 			err |= objerror(obj, _("non-tree in cache-tree"));
 	}
-	for (i = 0; i < it->subtree_nr; i++)
+	for (int i = 0; i < it->subtree_nr; i++)
 		err |= fsck_cache_tree(it->down[i]->cache_tree, index_path);
 	return err;
 }
@@ -809,11 +808,9 @@ static int fsck_resolve_undo(struct index_state *istate,
 static void fsck_index(struct index_state *istate, const char *index_path,
 		       int is_current_worktree)
 {
-	unsigned int i;
-
 	/* TODO: audit for interaction with sparse-index. */
 	ensure_full_index(istate);
-	for (i = 0; i < istate->cache_nr; i++) {
+	for (unsigned int i = 0; i < istate->cache_nr; i++) {
 		unsigned int mode;
 		struct blob *blob;
 		struct object *obj;
@@ -921,7 +918,6 @@ static struct option fsck_opts[] = {
 
 int cmd_fsck(int argc, const char **argv, const char *prefix)
 {
-	int i;
 	struct object_directory *odb;
 
 	/* fsck knows how to handle missing promisor objects */
@@ -994,7 +990,7 @@ int cmd_fsck(int argc, const char **argv, const char *prefix)
 			errors_found |= ERROR_OBJECT;
 	}
 
-	for (i = 0; i < argc; i++) {
+	for (int i = 0; i < argc; i++) {
 		const char *arg = argv[i];
 		struct object_id oid;
 		if (!repo_get_oid(the_repository, arg, &oid)) {
@@ -1030,13 +1026,13 @@ int cmd_fsck(int argc, const char **argv, const char *prefix)
 	}
 
 	if (keep_cache_objects) {
-		struct worktree **worktrees, **p;
+		struct worktree **worktrees;
 
 		verify_index_checksum = 1;
 		verify_ce_order = 1;
 
 		worktrees = get_worktrees();
-		for (p = worktrees; *p; p++) {
+		for (struct worktree **p = worktrees; *p; p++) {
 			struct worktree *wt = *p;
 			struct index_state istate =
 				INDEX_STATE_INIT(the_repository);
diff --git a/builtin/fsmonitor--daemon.c b/builtin/fsmonitor--daemon.c
index 1593713f4c..054e79dd03 100644
--- a/builtin/fsmonitor--daemon.c
+++ b/builtin/fsmonitor--daemon.c
@@ -227,12 +227,9 @@ static enum fsmonitor_cookie_item_result with_lock__wait_for_cookie(
 static void with_lock__mark_cookies_seen(struct fsmonitor_daemon_state *state,
 					 const struct string_list *cookie_names)
 {
-	/* assert current thread holding state->main_lock */
-
-	int k;
 	int nr_seen = 0;
 
-	for (k = 0; k < cookie_names->nr; k++) {
+	for (int k = 0; k < cookie_names->nr; k++) {
 		struct fsmonitor_cookie_item key;
 		struct fsmonitor_cookie_item *cookie;
 
@@ -468,13 +465,11 @@ void fsmonitor_batch__add_path(struct fsmonitor_batch *batch,
 static void fsmonitor_batch__combine(struct fsmonitor_batch *batch_dest,
 				     const struct fsmonitor_batch *batch_src)
 {
-	size_t k;
-
 	ALLOC_GROW(batch_dest->interned_paths,
 		   batch_dest->nr + batch_src->nr + 1,
 		   batch_dest->alloc);
 
-	for (k = 0; k < batch_src->nr; k++)
+	for (size_t k = 0; k < batch_src->nr; k++)
 		batch_dest->interned_paths[batch_dest->nr++] =
 			batch_src->interned_paths[k];
 }
@@ -512,9 +507,6 @@ static struct fsmonitor_batch *with_lock__truncate_old_batches(
 	struct fsmonitor_daemon_state *state,
 	const struct fsmonitor_batch *batch_marker)
 {
-	/* assert current thread holding state->main_lock */
-
-	const struct fsmonitor_batch *batch;
 	struct fsmonitor_batch *remainder;
 
 	if (!batch_marker)
@@ -524,7 +516,7 @@ static struct fsmonitor_batch *with_lock__truncate_old_batches(
 			 batch_marker->batch_seq_nr,
 			 (uint64_t)batch_marker->pinned_time);
 
-	for (batch = batch_marker; batch; batch = batch->next) {
+	for (const struct fsmonitor_batch *batch = batch_marker; batch; batch = batch->next) {
 		time_t t;
 
 		if (!batch->pinned_time) /* an overflow batch */
diff --git a/builtin/gc.c b/builtin/gc.c
index cb80ced6cb..1151f59d76 100644
--- a/builtin/gc.c
+++ b/builtin/gc.c
@@ -80,8 +80,7 @@ static struct string_list pack_garbage = STRING_LIST_INIT_DUP;
 
 static void clean_pack_garbage(void)
 {
-	int i;
-	for (i = 0; i < pack_garbage.nr; i++)
+	for (int i = 0; i < pack_garbage.nr; i++)
 		unlink_or_warn(pack_garbage.items[i].string);
 	string_list_clear(&pack_garbage, 0);
 }
@@ -226,9 +225,9 @@ static int too_many_loose_objects(void)
 static struct packed_git *find_base_packs(struct string_list *packs,
 					  unsigned long limit)
 {
-	struct packed_git *p, *base = NULL;
+	struct packed_git *base = NULL;
 
-	for (p = get_all_packs(the_repository); p; p = p->next) {
+	for (struct packed_git *p = get_all_packs(the_repository); p; p = p->next) {
 		if (!p->pack_local || p->is_cruft)
 			continue;
 		if (limit) {
@@ -1100,7 +1099,6 @@ static int maintenance_task_loose_objects(struct maintenance_run_opts *opts)
 
 static int incremental_repack_auto_condition(void)
 {
-	struct packed_git *p;
 	int incremental_repack_auto_limit = 10;
 	int count = 0;
 
@@ -1116,9 +1114,7 @@ static int incremental_repack_auto_condition(void)
 	if (incremental_repack_auto_limit < 0)
 		return 1;
 
-	for (p = get_packed_git(the_repository);
-	     count < incremental_repack_auto_limit && p;
-	     p = p->next) {
+	for (struct packed_git *p = get_packed_git(the_repository); count < incremental_repack_auto_limit && p; p = p->next) {
 		if (!p->multi_pack_index)
 			count++;
 	}
@@ -1177,11 +1173,10 @@ static off_t get_auto_pack_size(void)
 	off_t max_size = 0;
 	off_t second_largest_size = 0;
 	off_t result_size;
-	struct packed_git *p;
 	struct repository *r = the_repository;
 
 	reprepare_packed_git(r);
-	for (p = get_all_packs(r); p; p = p->next) {
+	for (struct packed_git *p = get_all_packs(r); p; p = p->next) {
 		if (p->pack_size > max_size) {
 			second_largest_size = max_size;
 			max_size = p->pack_size;
@@ -1389,14 +1384,13 @@ static void initialize_maintenance_strategy(void)
 
 static void initialize_task_config(int schedule)
 {
-	int i;
 	struct strbuf config_name = STRBUF_INIT;
 	gc_config();
 
 	if (schedule)
 		initialize_maintenance_strategy();
 
-	for (i = 0; i < TASK__COUNT; i++) {
+	for (int i = 0; i < TASK__COUNT; i++) {
 		int config_value;
 		char *config_str;
 
@@ -1423,12 +1417,12 @@ static void initialize_task_config(int schedule)
 static int task_option_parse(const struct option *opt UNUSED,
 			     const char *arg, int unset)
 {
-	int i, num_selected = 0;
+	int num_selected = 0;
 	struct maintenance_task *task = NULL;
 
 	BUG_ON_OPT_NEG(unset);
 
-	for (i = 0; i < TASK__COUNT; i++) {
+	for (int i = 0; i < TASK__COUNT; i++) {
 		if (tasks[i].selected_order >= 0)
 			num_selected++;
 		if (!strcasecmp(tasks[i].name, arg)) {
@@ -1453,7 +1447,6 @@ static int task_option_parse(const struct option *opt UNUSED,
 
 static int maintenance_run(int argc, const char **argv, const char *prefix)
 {
-	int i;
 	struct maintenance_run_opts opts;
 	struct option builtin_maintenance_run_options[] = {
 		OPT_BOOL(0, "auto", &opts.auto_flag,
@@ -1472,7 +1465,7 @@ static int maintenance_run(int argc, const char **argv, const char *prefix)
 
 	opts.quiet = !isatty(2);
 
-	for (i = 0; i < TASK__COUNT; i++)
+	for (int i = 0; i < TASK__COUNT; i++)
 		tasks[i].selected_order = -1;
 
 	argc = parse_options(argc, argv, prefix,
@@ -2691,7 +2684,6 @@ static void validate_scheduler(enum scheduler scheduler)
 static int update_background_schedule(const struct maintenance_start_opts *opts,
 				      int enable)
 {
-	unsigned int i;
 	int result = 0;
 	struct lock_file lk;
 	char *lock_path = xstrfmt("%s/schedule", the_repository->objects->odb->path);
@@ -2701,7 +2693,7 @@ static int update_background_schedule(const struct maintenance_start_opts *opts,
 		return error(_("another process is scheduling background maintenance"));
 	}
 
-	for (i = 1; i < ARRAY_SIZE(scheduler_fn); i++) {
+	for (unsigned int i = 1; i < ARRAY_SIZE(scheduler_fn); i++) {
 		if (enable && opts->scheduler == i)
 			continue;
 		if (!scheduler_fn[i].is_available())
diff --git a/builtin/grep.c b/builtin/grep.c
index 982bcfc4b1..ebb61eec1b 100644
--- a/builtin/grep.c
+++ b/builtin/grep.c
@@ -179,9 +179,7 @@ static void work_done(struct work_item *w)
 
 static void free_repos(void)
 {
-	int i;
-
-	for (i = 0; i < repos_to_free_nr; i++) {
+	for (int i = 0; i < repos_to_free_nr; i++) {
 		repo_clear(repos_to_free[i]);
 		free(repos_to_free[i]);
 	}
@@ -250,7 +248,6 @@ static void start_threads(struct grep_opt *opt)
 static int wait_all(void)
 {
 	int hit = 0;
-	int i;
 
 	if (!HAVE_THREADS)
 		BUG("Never call this function unless you have started threads");
@@ -268,7 +265,7 @@ static int wait_all(void)
 	pthread_cond_broadcast(&cond_add);
 	grep_unlock();
 
-	for (i = 0; i < num_threads; i++) {
+	for (int i = 0; i < num_threads; i++) {
 		void *h;
 		pthread_join(threads[i], &h);
 		hit |= (int) (intptr_t) h;
@@ -418,9 +415,9 @@ static void run_pager(struct grep_opt *opt, const char *prefix)
 {
 	struct string_list *path_list = opt->output_priv;
 	struct child_process child = CHILD_PROCESS_INIT;
-	int i, status;
+	int status;
 
-	for (i = 0; i < path_list->nr; i++)
+	for (int i = 0; i < path_list->nr; i++)
 		strvec_push(&child.args, path_list->items[i].string);
 	child.dir = prefix;
 	child.use_shell = 1;
@@ -544,7 +541,6 @@ static int grep_cache(struct grep_opt *opt,
 {
 	struct repository *repo = opt->repo;
 	int hit = 0;
-	int nr;
 	struct strbuf name = STRBUF_INIT;
 	int name_base_len = 0;
 	if (repo->submodule_prefix) {
@@ -555,7 +551,7 @@ static int grep_cache(struct grep_opt *opt,
 	if (repo_read_index(repo) < 0)
 		die(_("index file corrupt"));
 
-	for (nr = 0; nr < repo->index->cache_nr; nr++) {
+	for (int nr = 0; nr < repo->index->cache_nr; nr++) {
 		const struct cache_entry *ce = repo->index->cache[nr];
 
 		if (!cached && ce_skip_worktree(ce))
@@ -726,11 +722,10 @@ static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
 static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
 			const struct object_array *list)
 {
-	unsigned int i;
 	int hit = 0;
 	const unsigned int nr = list->nr;
 
-	for (i = 0; i < nr; i++) {
+	for (unsigned int i = 0; i < nr; i++) {
 		struct object *real_obj;
 
 		obj_read_lock();
@@ -770,7 +765,7 @@ static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
 			  int exc_std, int use_index)
 {
 	struct dir_struct dir = DIR_INIT;
-	int i, hit = 0;
+	int hit = 0;
 
 	if (!use_index)
 		dir.flags |= DIR_NO_GITLINKS;
@@ -778,7 +773,7 @@ static int grep_directory(struct grep_opt *opt, const struct pathspec *pathspec,
 		setup_standard_excludes(&dir);
 
 	fill_directory(&dir, opt->repo->index, pathspec);
-	for (i = 0; i < dir.nr; i++) {
+	for (int i = 0; i < dir.nr; i++) {
 		hit |= grep_file(opt, dir.entries[i]->name);
 		if (hit && opt->status_only)
 			break;
@@ -1148,8 +1143,7 @@ int cmd_grep(int argc, const char **argv, const char *prefix)
 	 * "do what I mean" case, we verify and complain when that isn't true.
 	 */
 	if (!seen_dashdash) {
-		int j;
-		for (j = i; j < argc; j++)
+		for (int j = i; j < argc; j++)
 			verify_filename(prefix, argv[j], j == i && allow_revs);
 	}
 
diff --git a/builtin/hash-object.c b/builtin/hash-object.c
index 82ca6d2bfd..5cefac6ef8 100644
--- a/builtin/hash-object.c
+++ b/builtin/hash-object.c
@@ -112,7 +112,6 @@ int cmd_hash_object(int argc, const char **argv, const char *prefix)
 		OPT_STRING( 0 , "path", &vpath, N_("file"), N_("process file as it were from this path")),
 		OPT_END()
 	};
-	int i;
 	const char *errstr = NULL;
 
 	argc = parse_options(argc, argv, prefix, hash_object_options,
@@ -153,7 +152,7 @@ int cmd_hash_object(int argc, const char **argv, const char *prefix)
 	if (hashstdin)
 		hash_fd(0, type, vpath, flags, literally);
 
-	for (i = 0 ; i < argc; i++) {
+	for (int i = 0; i < argc; i++) {
 		const char *arg = argv[i];
 		char *to_free = NULL;
 
diff --git a/builtin/help.c b/builtin/help.c
index dc1fbe2b98..cea3415a17 100644
--- a/builtin/help.c
+++ b/builtin/help.c
@@ -122,14 +122,11 @@ static void list_config_help(enum show_config_type type)
 		{ "receive.fsck", "<msg-id>", list_config_fsck_msg_ids },
 		{ NULL, NULL, NULL }
 	};
-	const char **p;
 	struct slot_expansion *e;
 	struct string_list keys = STRING_LIST_INIT_DUP;
 	struct string_list keys_uniq = STRING_LIST_INIT_DUP;
 	struct string_list_item *item;
-	int i;
-
-	for (p = config_name_list; *p; p++) {
+	for (const char **p = config_name_list; *p; p++) {
 		const char *var = *p;
 		struct strbuf sb = STRBUF_INIT;
 
@@ -154,7 +151,7 @@ static void list_config_help(enum show_config_type type)
 			    e->prefix, e->placeholder);
 
 	string_list_sort(&keys);
-	for (i = 0; i < keys.nr; i++) {
+	for (int i = 0; i < keys.nr; i++) {
 		const char *var = keys.items[i].string;
 		const char *wildcard, *tag, *cut;
 		const char *dot = NULL;
@@ -216,9 +213,7 @@ static enum help_format parse_help_format(const char *format)
 
 static const char *get_man_viewer_info(const char *name)
 {
-	struct man_viewer_info_list *viewer;
-
-	for (viewer = man_viewer_info_list; viewer; viewer = viewer->next)
+	for (struct man_viewer_info_list *viewer = man_viewer_info_list; viewer; viewer = viewer->next)
 	{
 		if (!strcasecmp(name, viewer->name))
 			return viewer->info;
@@ -489,11 +484,10 @@ static void exec_viewer(const char *name, const char *page)
 
 static void show_man_page(const char *page)
 {
-	struct man_viewer_list *viewer;
 	const char *fallback = getenv("GIT_MAN_VIEWER");
 
 	setup_man_path();
-	for (viewer = man_viewer_list; viewer; viewer = viewer->next)
+	for (struct man_viewer_list *viewer = man_viewer_list; viewer; viewer = viewer->next)
 	{
 		exec_viewer(viewer->name, page); /* will return when unable */
 	}
diff --git a/builtin/hook.c b/builtin/hook.c
index 5234693a94..9015f47532 100644
--- a/builtin/hook.c
+++ b/builtin/hook.c
@@ -20,7 +20,6 @@ static const char * const builtin_hook_run_usage[] = {
 
 static int run(int argc, const char **argv, const char *prefix)
 {
-	int i;
 	struct run_hooks_opt opt = RUN_HOOKS_OPT_INIT;
 	int ignore_missing = 0;
 	const char *hook_name;
@@ -49,7 +48,7 @@ static int run(int argc, const char **argv, const char *prefix)
 		goto usage;
 
 	/* Add our arguments, start after -- */
-	for (i = 2 ; i < argc; i++)
+	for (int i = 2; i < argc; i++)
 		strvec_push(&opt.args, argv[i]);
 
 	/* Need to take into account core.hooksPath */
diff --git a/builtin/index-pack.c b/builtin/index-pack.c
index a3a37bd215..f3489b51e7 100644
--- a/builtin/index-pack.c
+++ b/builtin/index-pack.c
@@ -186,7 +186,6 @@ static inline void unlock_mutex(pthread_mutex_t *mutex)
  */
 static void init_thread(void)
 {
-	int i;
 	init_recursive_mutex(&read_mutex);
 	pthread_mutex_init(&counter_mutex, NULL);
 	pthread_mutex_init(&work_mutex, NULL);
@@ -194,7 +193,7 @@ static void init_thread(void)
 		pthread_mutex_init(&deepest_delta_mutex, NULL);
 	pthread_key_create(&key, NULL);
 	CALLOC_ARRAY(thread_data, nr_threads);
-	for (i = 0; i < nr_threads; i++) {
+	for (int i = 0; i < nr_threads; i++) {
 		thread_data[i].pack_fd = xopen(curr_pack, O_RDONLY);
 	}
 
@@ -203,7 +202,6 @@ static void init_thread(void)
 
 static void cleanup_thread(void)
 {
-	int i;
 	if (!threads_active)
 		return;
 	threads_active = 0;
@@ -212,7 +210,7 @@ static void cleanup_thread(void)
 	pthread_mutex_destroy(&work_mutex);
 	if (show_stat)
 		pthread_mutex_destroy(&deepest_delta_mutex);
-	for (i = 0; i < nr_threads; i++)
+	for (int i = 0; i < nr_threads; i++)
 		close(thread_data[i].pack_fd);
 	pthread_key_delete(key);
 	free(thread_data);
@@ -261,14 +259,14 @@ static unsigned check_object(struct object *obj)
 
 static unsigned check_objects(void)
 {
-	unsigned i, max, foreign_nr = 0;
+	unsigned max, foreign_nr = 0;
 
 	max = get_max_object_index();
 
 	if (verbose)
 		progress = start_delayed_progress(_("Checking objects"), max);
 
-	for (i = 0; i < max; i++) {
+	for (unsigned i = 0; i < max; i++) {
 		foreign_nr += check_object(get_indexed_object(i));
 		display_progress(progress, i + 1);
 	}
@@ -1627,7 +1625,6 @@ static void read_v2_anomalous_offsets(struct packed_git *p,
 				      struct pack_idx_option *opts)
 {
 	const uint32_t *idx1, *idx2;
-	uint32_t i;
 
 	/* The address of the 4-byte offset table */
 	idx1 = (((const uint32_t *)((const uint8_t *)p->index_data + p->crc_offset))
@@ -1637,7 +1634,7 @@ static void read_v2_anomalous_offsets(struct packed_git *p,
 	/* The address of the 8-byte offset table */
 	idx2 = idx1 + p->num_objects;
 
-	for (i = 0; i < p->num_objects; i++) {
+	for (uint32_t i = 0; i < p->num_objects; i++) {
 		uint32_t off = ntohl(idx1[i]);
 		if (!(off & 0x80000000))
 			continue;
diff --git a/builtin/interpret-trailers.c b/builtin/interpret-trailers.c
index 033bd1556c..cd6f32bbd5 100644
--- a/builtin/interpret-trailers.c
+++ b/builtin/interpret-trailers.c
@@ -130,8 +130,7 @@ int cmd_interpret_trailers(int argc, const char **argv, const char *prefix)
 			options);
 
 	if (argc) {
-		int i;
-		for (i = 0; i < argc; i++)
+		for (int i = 0; i < argc; i++)
 			process_trailers(argv[i], &opts, &trailers);
 	} else {
 		if (opts.in_place)
diff --git a/builtin/log.c b/builtin/log.c
index db1808d7c1..eb3d9f7623 100644
--- a/builtin/log.c
+++ b/builtin/log.c
@@ -190,7 +190,6 @@ static void cmd_log_init_defaults(struct rev_info *rev)
 
 static void set_default_decoration_filter(struct decoration_filter *decoration_filter)
 {
-	int i;
 	char *value = NULL;
 	struct string_list *include = decoration_filter->include_ref_pattern;
 	const struct string_list *config_exclude;
@@ -224,7 +223,7 @@ static void set_default_decoration_filter(struct decoration_filter *decoration_f
 	 * No command-line or config options were given, so
 	 * populate with sensible defaults.
 	 */
-	for (i = 0; i < ARRAY_SIZE(ref_namespace); i++) {
+	for (int i = 0; i < ARRAY_SIZE(ref_namespace); i++) {
 		if (!ref_namespace[i].decoration)
 			continue;
 
@@ -734,7 +733,6 @@ static void show_setup_revisions_tweak(struct rev_info *rev)
 int cmd_show(int argc, const char **argv, const char *prefix)
 {
 	struct rev_info rev;
-	unsigned int i;
 	struct setup_revision_opt opt;
 	struct pathspec match_all;
 	int ret = 0;
@@ -765,7 +763,7 @@ int cmd_show(int argc, const char **argv, const char *prefix)
 		return cmd_log_deinit(cmd_log_walk(&rev), &rev);
 
 	rev.diffopt.no_free = 1;
-	for (i = 0; i < rev.pending.nr && !ret; i++) {
+	for (unsigned int i = 0; i < rev.pending.nr && !ret; i++) {
 		struct object *o = rev.pending.objects[i].item;
 		const char *name = rev.pending.objects[i].name;
 		switch (o->type) {
@@ -1211,13 +1209,13 @@ static void print_signature(FILE *file)
 
 static char *find_branch_name(struct rev_info *rev)
 {
-	int i, positive = -1;
+	int positive = -1;
 	struct object_id branch_oid;
 	const struct object_id *tip_oid;
 	const char *ref, *v;
 	char *full_ref, *branch = NULL;
 
-	for (i = 0; i < rev->cmdline.nr; i++) {
+	for (int i = 0; i < rev->cmdline.nr; i++) {
 		if (rev->cmdline.rev[i].flags & UNINTERESTING)
 			continue;
 		if (positive < 0)
@@ -1760,7 +1758,6 @@ static void prepare_bases(struct base_tree_info *bases,
 	struct rev_info revs;
 	struct diff_options diffopt;
 	struct commit_base commit_base;
-	int i;
 
 	if (!base)
 		return;
@@ -1775,7 +1772,7 @@ static void prepare_bases(struct base_tree_info *bases,
 	repo_init_revisions(the_repository, &revs, NULL);
 	revs.max_parents = 1;
 	revs.topo_order = 1;
-	for (i = 0; i < total; i++) {
+	for (int i = 0; i < total; i++) {
 		list[i]->object.flags &= ~UNINTERESTING;
 		add_pending_object(&revs, &list[i]->object, "rev_list");
 		*commit_base_at(&commit_base, list[i]) = 1;
@@ -1806,8 +1803,6 @@ static void prepare_bases(struct base_tree_info *bases,
 
 static void print_bases(struct base_tree_info *bases, FILE *file)
 {
-	int i;
-
 	/* Only do this once, either for the cover or for the first one */
 	if (is_null_oid(&bases->base_commit))
 		return;
@@ -1816,7 +1811,7 @@ static void print_bases(struct base_tree_info *bases, FILE *file)
 	fprintf(file, "\nbase-commit: %s\n", oid_to_hex(&bases->base_commit));
 
 	/* Show the prerequisite patches */
-	for (i = bases->nr_patch_id - 1; i >= 0; i--)
+	for (int i = bases->nr_patch_id - 1; i >= 0; i--)
 		fprintf(file, "prerequisite-patch-id: %s\n", oid_to_hex(&bases->patch_id[i]));
 
 	free(bases->patch_id);
diff --git a/builtin/ls-files.c b/builtin/ls-files.c
index 92f94e65bf..e8ceb86599 100644
--- a/builtin/ls-files.c
+++ b/builtin/ls-files.c
@@ -163,9 +163,7 @@ static void show_dir_entry(struct index_state *istate,
 static void show_other_files(struct index_state *istate,
 			     const struct dir_struct *dir)
 {
-	int i;
-
-	for (i = 0; i < dir->nr; i++) {
+	for (int i = 0; i < dir->nr; i++) {
 		struct dir_entry *ent = dir->entries[i];
 		if (!index_name_is_other(istate, ent->name, ent->len))
 			continue;
@@ -176,8 +174,7 @@ static void show_other_files(struct index_state *istate,
 static void show_killed_files(struct index_state *istate,
 			      const struct dir_struct *dir)
 {
-	int i;
-	for (i = 0; i < dir->nr; i++) {
+	for (int i = 0; i < dir->nr; i++) {
 		struct dir_entry *ent = dir->entries[i];
 		char *cp, *sp;
 		int pos, len, killed = 0;
@@ -400,7 +397,6 @@ static void construct_fullname(struct strbuf *out, const struct repository *repo
 
 static void show_files(struct repository *repo, struct dir_struct *dir)
 {
-	int i;
 	struct strbuf fullname = STRBUF_INIT;
 
 	/* For cached/deleted files we don't need to even do the readdir */
@@ -420,7 +416,7 @@ static void show_files(struct repository *repo, struct dir_struct *dir)
 	if (!show_sparse_dirs)
 		ensure_full_index(repo->index);
 
-	for (i = 0; i < repo->index->cache_nr; i++) {
+	for (int i = 0; i < repo->index->cache_nr; i++) {
 		const struct cache_entry *ce = repo->index->cache[i];
 		struct stat st;
 		int stat_err;
@@ -571,7 +567,7 @@ static int option_parse_exclude_standard(const struct option *opt,
 
 int cmd_ls_files(int argc, const char **argv, const char *cmd_prefix)
 {
-	int require_work_tree = 0, show_tag = 0, i;
+	int require_work_tree = 0, show_tag = 0;
 	char *max_prefix;
 	struct dir_struct dir = DIR_INIT;
 	struct pattern_list *pl;
@@ -663,7 +659,7 @@ int cmd_ls_files(int argc, const char **argv, const char *cmd_prefix)
 	argc = parse_options(argc, argv, prefix, builtin_ls_files_options,
 			ls_files_usage, 0);
 	pl = add_pattern_list(&dir, EXC_CMDL, "--exclude option");
-	for (i = 0; i < exclude_list.nr; i++) {
+	for (int i = 0; i < exclude_list.nr; i++) {
 		add_pattern(exclude_list.items[i].string, "", 0, pl, --exclude_args);
 	}
 
diff --git a/builtin/ls-tree.c b/builtin/ls-tree.c
index e4a891337c..24d21dbad6 100644
--- a/builtin/ls-tree.c
+++ b/builtin/ls-tree.c
@@ -55,15 +55,13 @@ struct ls_tree_options {
 static int show_recursive(struct ls_tree_options *options, const char *base,
 			  size_t baselen, const char *pathname)
 {
-	int i;
-
 	if (options->ls_options & LS_RECURSIVE)
 		return 1;
 
 	if (!options->pathspec.nr)
 		return 0;
 
-	for (i = 0; i < options->pathspec.nr; i++) {
+	for (int i = 0; i < options->pathspec.nr; i++) {
 		const char *spec = options->pathspec.items[i].match;
 		size_t len, speclen;
 
@@ -341,7 +339,7 @@ int cmd_ls_tree(int argc, const char **argv, const char *prefix)
 {
 	struct object_id oid;
 	struct tree *tree;
-	int i, full_tree = 0;
+	int full_tree = 0;
 	int full_name = !prefix || !*prefix;
 	read_tree_fn_t fn = NULL;
 	enum ls_tree_cmdmode cmdmode = MODE_DEFAULT;
@@ -419,7 +417,7 @@ int cmd_ls_tree(int argc, const char **argv, const char *prefix)
 		       ~(PATHSPEC_FROMTOP | PATHSPEC_LITERAL),
 		       PATHSPEC_PREFER_CWD,
 		       prefix, argv + 1);
-	for (i = 0; i < options.pathspec.nr; i++)
+	for (int i = 0; i < options.pathspec.nr; i++)
 		options.pathspec.items[i].nowildcard_len = options.pathspec.items[i].len;
 	options.pathspec.has_wildcard = 0;
 	tree = parse_tree_indirect(&oid);
diff --git a/builtin/mailsplit.c b/builtin/mailsplit.c
index 3af9ddb8ae..ccb52fbc4b 100644
--- a/builtin/mailsplit.c
+++ b/builtin/mailsplit.c
@@ -114,10 +114,9 @@ static int populate_maildir_list(struct string_list *list, const char *path)
 	struct dirent *dent;
 	char *name = NULL;
 	char *subs[] = { "cur", "new", NULL };
-	char **sub;
 	int ret = -1;
 
-	for (sub = subs; *sub; ++sub) {
+	for (char **sub = subs; *sub; ++sub) {
 		free(name);
 		name = xstrfmt("%s/%s", path, *sub);
 		if (!(dir = opendir(name))) {
@@ -172,7 +171,6 @@ static int split_maildir(const char *maildir, const char *dir,
 	char *file = NULL;
 	FILE *f = NULL;
 	int ret = -1;
-	int i;
 	struct string_list list = STRING_LIST_INIT_DUP;
 
 	list.cmp = maildir_filename_cmp;
@@ -180,7 +178,7 @@ static int split_maildir(const char *maildir, const char *dir,
 	if (populate_maildir_list(&list, maildir) < 0)
 		goto out;
 
-	for (i = 0; i < list.nr; i++) {
+	for (int i = 0; i < list.nr; i++) {
 		char *name;
 
 		free(file);
diff --git a/builtin/merge-base.c b/builtin/merge-base.c
index d26e8fbf6f..2c66380e3b 100644
--- a/builtin/merge-base.c
+++ b/builtin/merge-base.c
@@ -10,7 +10,7 @@
 
 static int show_merge_base(struct commit **rev, int rev_nr, int show_all)
 {
-	struct commit_list *result, *r;
+	struct commit_list *result;
 
 	result = repo_get_merge_bases_many_dirty(the_repository, rev[0],
 						 rev_nr - 1, rev + 1);
@@ -18,7 +18,7 @@ static int show_merge_base(struct commit **rev, int rev_nr, int show_all)
 	if (!result)
 		return 1;
 
-	for (r = result; r; r = r->next) {
+	for (struct commit_list *r = result; r; r = r->next) {
 		printf("%s\n", oid_to_hex(&r->item->object.oid));
 		if (!show_all)
 			break;
@@ -53,10 +53,8 @@ static struct commit *get_commit_reference(const char *arg)
 
 static int handle_independent(int count, const char **args)
 {
-	struct commit_list *revs = NULL, *rev;
-	int i;
-
-	for (i = count - 1; i >= 0; i--)
+	struct commit_list *revs = NULL;
+	for (int i = count - 1; i >= 0; i--)
 		commit_list_insert(get_commit_reference(args[i]), &revs);
 
 	reduce_heads_replace(&revs);
@@ -64,7 +62,7 @@ static int handle_independent(int count, const char **args)
 	if (!revs)
 		return 1;
 
-	for (rev = revs; rev; rev = rev->next)
+	for (struct commit_list *rev = revs; rev; rev = rev->next)
 		printf("%s\n", oid_to_hex(&rev->item->object.oid));
 
 	free_commit_list(revs);
@@ -74,10 +72,8 @@ static int handle_independent(int count, const char **args)
 static int handle_octopus(int count, const char **args, int show_all)
 {
 	struct commit_list *revs = NULL;
-	struct commit_list *result, *rev;
-	int i;
-
-	for (i = count - 1; i >= 0; i--)
+	struct commit_list *result;
+	for (int i = count - 1; i >= 0; i--)
 		commit_list_insert(get_commit_reference(args[i]), &revs);
 
 	result = get_octopus_merge_bases(revs);
@@ -87,7 +83,7 @@ static int handle_octopus(int count, const char **args, int show_all)
 	if (!result)
 		return 1;
 
-	for (rev = result; rev; rev = rev->next) {
+	for (struct commit_list *rev = result; rev; rev = rev->next) {
 		printf("%s\n", oid_to_hex(&rev->item->object.oid));
 		if (!show_all)
 			break;
diff --git a/builtin/merge-index.c b/builtin/merge-index.c
index 270d5f644a..39a0535d56 100644
--- a/builtin/merge-index.c
+++ b/builtin/merge-index.c
@@ -63,10 +63,9 @@ static void merge_one_path(const char *path)
 
 static void merge_all(void)
 {
-	int i;
 	/* TODO: audit for interaction with sparse-index. */
 	ensure_full_index(&the_index);
-	for (i = 0; i < the_index.cache_nr; i++) {
+	for (int i = 0; i < the_index.cache_nr; i++) {
 		const struct cache_entry *ce = the_index.cache[i];
 		if (!ce_stage(ce))
 			continue;
diff --git a/builtin/merge-tree.c b/builtin/merge-tree.c
index cbd8e15af6..72e0844ad1 100644
--- a/builtin/merge-tree.c
+++ b/builtin/merge-tree.c
@@ -109,8 +109,7 @@ static void *origin(struct merge_list *entry, unsigned long *size)
 
 static int show_outf(void *priv UNUSED, mmbuffer_t *mb, int nbuf)
 {
-	int i;
-	for (i = 0; i < nbuf; i++)
+	for (int i = 0; i < nbuf; i++)
 		printf("%.*s", (int) mb[i].size, mb[i].ptr);
 	return 0;
 }
@@ -267,10 +266,9 @@ static struct merge_list *link_entry(unsigned stage, const struct traverse_info
 static void unresolved(const struct traverse_info *info, struct name_entry n[3])
 {
 	struct merge_list *entry = NULL;
-	int i;
 	unsigned dirmask = 0, mask = 0;
 
-	for (i = 0; i < 3; i++) {
+	for (int i = 0; i < 3; i++) {
 		mask |= (1 << i);
 		/*
 		 * Treat missing entries as directories so that we return
@@ -490,10 +488,9 @@ static int real_merge(struct merge_tree_options *o,
 	if (!result.clean) {
 		struct string_list conflicted_files = STRING_LIST_INIT_NODUP;
 		const char *last = NULL;
-		int i;
 
 		merge_get_conflicted_files(&result, &conflicted_files);
-		for (i = 0; i < conflicted_files.nr; i++) {
+		for (int i = 0; i < conflicted_files.nr; i++) {
 			const char *name = conflicted_files.items[i].string;
 			struct stage_info *c = conflicted_files.items[i].util;
 			if (!o->name_only)
diff --git a/builtin/merge.c b/builtin/merge.c
index 935c8a57dd..df0650348d 100644
--- a/builtin/merge.c
+++ b/builtin/merge.c
@@ -393,7 +393,6 @@ static void squash_message(struct commit *commit, struct commit_list *remotehead
 {
 	struct rev_info rev;
 	struct strbuf out = STRBUF_INIT;
-	struct commit_list *j;
 	struct pretty_print_context ctx = {0};
 
 	printf(_("Squash commit -- not updating HEAD\n"));
@@ -405,7 +404,7 @@ static void squash_message(struct commit *commit, struct commit_list *remotehead
 	commit->object.flags |= UNINTERESTING;
 	add_pending_object(&rev, &commit->object, NULL);
 
-	for (j = remoteheads; j; j = j->next)
+	for (struct commit_list *j = remoteheads; j; j = j->next)
 		add_pending_object(&rev, &j->item->object, NULL);
 
 	setup_revisions(0, NULL, &rev, NULL);
@@ -650,7 +649,7 @@ static int git_merge_config(const char *k, const char *v,
 static int read_tree_trivial(struct object_id *common, struct object_id *head,
 			     struct object_id *one)
 {
-	int i, nr_trees = 0;
+	int nr_trees = 0;
 	struct tree *trees[MAX_UNPACK_TREES];
 	struct tree_desc t[MAX_UNPACK_TREES];
 	struct unpack_trees_options opts;
@@ -675,7 +674,7 @@ static int read_tree_trivial(struct object_id *common, struct object_id *head,
 		return -1;
 	opts.fn = threeway_merge;
 	cache_tree_free(&the_index.cache_tree);
-	for (i = 0; i < nr_trees; i++) {
+	for (int i = 0; i < nr_trees; i++) {
 		parse_tree(trees[i]);
 		init_tree_desc(t+i, trees[i]->buffer, trees[i]->size);
 	}
@@ -704,11 +703,10 @@ static int try_merge_strategy(const char *strategy, struct commit_list *common,
 	if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree") ||
 	    !strcmp(strategy, "ort")) {
 		struct lock_file lock = LOCK_INIT;
-		int clean, x;
+		int clean;
 		struct commit *result;
 		struct commit_list *reversed = NULL;
 		struct merge_options o;
-		struct commit_list *j;
 
 		if (remoteheads->next) {
 			error(_("Not handling anything other than two heads merge."));
@@ -722,14 +720,14 @@ static int try_merge_strategy(const char *strategy, struct commit_list *common,
 		o.show_rename_progress =
 			show_progress == -1 ? isatty(2) : show_progress;
 
-		for (x = 0; x < xopts.nr; x++)
+		for (int x = 0; x < xopts.nr; x++)
 			if (parse_merge_opt(&o, xopts.v[x]))
 				die(_("unknown strategy option: -X%s"), xopts.v[x]);
 
 		o.branch1 = head_arg;
 		o.branch2 = merge_remote_util(remoteheads->item)->name;
 
-		for (j = common; j; j = j->next)
+		for (struct commit_list *j = common; j; j = j->next)
 			commit_list_insert(j->item, &reversed);
 
 		repo_hold_locked_index(the_repository, &lock,
@@ -765,9 +763,9 @@ static void count_diff_files(struct diff_queue_struct *q,
 
 static int count_unmerged_entries(void)
 {
-	int i, ret = 0;
+	int ret = 0;
 
-	for (i = 0; i < the_index.cache_nr; i++)
+	for (int i = 0; i < the_index.cache_nr; i++)
 		if (ce_stage(the_index.cache[i]))
 			ret++;
 
@@ -776,8 +774,6 @@ static int count_unmerged_entries(void)
 
 static void add_strategies(const char *string, unsigned attr)
 {
-	int i;
-
 	if (string) {
 		struct string_list list = STRING_LIST_INIT_DUP;
 		struct string_list_item *item;
@@ -787,7 +783,7 @@ static void add_strategies(const char *string, unsigned attr)
 		string_list_clear(&list, 0);
 		return;
 	}
-	for (i = 0; i < ARRAY_SIZE(all_strategy); i++)
+	for (int i = 0; i < ARRAY_SIZE(all_strategy); i++)
 		if (all_strategy[i].attr & attr)
 			append_strategy(&all_strategy[i]);
 
@@ -1022,10 +1018,9 @@ static int setup_with_upstream(const char ***argv)
 
 static void write_merge_heads(struct commit_list *remoteheads)
 {
-	struct commit_list *j;
 	struct strbuf buf = STRBUF_INIT;
 
-	for (j = remoteheads; j; j = j->next) {
+	for (struct commit_list *j = remoteheads; j; j = j->next) {
 		struct object_id *oid;
 		struct commit *c = j->item;
 		struct merge_remote_desc *desc;
@@ -1130,7 +1125,7 @@ static void prepare_merge_message(struct strbuf *merge_names, struct strbuf *mer
 static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge_names)
 {
 	const char *filename;
-	int fd, pos, npos;
+	int fd, npos;
 	struct strbuf fetch_head_file = STRBUF_INIT;
 	const unsigned hexsz = the_hash_algo->hexsz;
 
@@ -1145,7 +1140,7 @@ static void handle_fetch_head(struct commit_list **remotes, struct strbuf *merge
 	if (close(fd) < 0)
 		die_errno(_("could not close '%s'"), filename);
 
-	for (pos = 0; pos < merge_names->len; pos = npos) {
+	for (int pos = 0; pos < merge_names->len; pos = npos) {
 		struct object_id oid;
 		char *ptr;
 		struct commit *commit;
@@ -1209,8 +1204,7 @@ static struct commit_list *collect_parents(struct commit *head_commit,
 		}
 		remoteheads = reduce_parents(head_commit, head_subsumed, remoteheads);
 		if (autogen) {
-			struct commit_list *p;
-			for (p = remoteheads; p; p = p->next)
+			for (struct commit_list *p = remoteheads; p; p = p->next)
 				merge_name(merge_remote_util(p->item)->name, autogen);
 		}
 	}
@@ -1623,9 +1617,7 @@ int cmd_merge(int argc, const char **argv, const char *prefix)
 		 * to date.
 		 */
 		int up_to_date = 1;
-		struct commit_list *j;
-
-		for (j = remoteheads; j; j = j->next) {
+		for (struct commit_list *j = remoteheads; j; j = j->next) {
 			struct commit_list *common_one;
 			struct commit *common_item;
 
diff --git a/builtin/name-rev.c b/builtin/name-rev.c
index 2dd1807c4e..3689e898f8 100644
--- a/builtin/name-rev.c
+++ b/builtin/name-rev.c
@@ -417,14 +417,12 @@ static int name_ref(const char *path, const struct object_id *oid,
 
 static void name_tips(void)
 {
-	int i;
-
 	/*
 	 * Try to set better names first, so that worse ones spread
 	 * less.
 	 */
 	QSORT(tip_table.table, tip_table.nr, cmp_by_tag_and_age);
-	for (i = 0; i < tip_table.nr; i++) {
+	for (int i = 0; i < tip_table.nr; i++) {
 		struct tip_table_entry *e = &tip_table.table[i];
 		if (e->commit) {
 			name_rev(e->commit, e->refname, e->taggerdate,
@@ -659,10 +657,10 @@ int cmd_name_rev(int argc, const char **argv, const char *prefix)
 		}
 		strbuf_release(&sb);
 	} else if (all) {
-		int i, max;
+		int max;
 
 		max = get_max_object_index();
-		for (i = 0; i < max; i++) {
+		for (int i = 0; i < max; i++) {
 			struct object *obj = get_indexed_object(i);
 			if (!obj || obj->type != OBJ_COMMIT)
 				continue;
@@ -670,8 +668,7 @@ int cmd_name_rev(int argc, const char **argv, const char *prefix)
 				  always, allow_undefined, data.name_only);
 		}
 	} else {
-		int i;
-		for (i = 0; i < revs.nr; i++)
+		for (int i = 0; i < revs.nr; i++)
 			show_name(revs.objects[i].item, revs.objects[i].name,
 				  always, allow_undefined, data.name_only);
 	}
diff --git a/builtin/notes.c b/builtin/notes.c
index caf20fd5bd..75c57e745c 100644
--- a/builtin/notes.c
+++ b/builtin/notes.c
@@ -254,9 +254,7 @@ static void append_separator(struct strbuf *message)
 static void concat_messages(struct note_data *d)
 {
 	struct strbuf msg = STRBUF_INIT;
-	size_t i;
-
-	for (i = 0; i < d->msg_nr ; i++) {
+	for (size_t i = 0; i < d->msg_nr; i++) {
 		if (d->buf.len)
 			append_separator(&d->buf);
 		strbuf_add(&msg, d->messages[i]->buf.buf, d->messages[i]->buf.len);
diff --git a/builtin/pack-objects.c b/builtin/pack-objects.c
index 329aeac804..3e3150198b 100644
--- a/builtin/pack-objects.c
+++ b/builtin/pack-objects.c
@@ -1549,7 +1549,6 @@ static int want_object_in_pack(const struct object_id *oid,
 {
 	int want;
 	struct list_head *pos;
-	struct multi_pack_index *m;
 
 	if (!exclude && local && has_loose_object_nonlocal(oid))
 		return 0;
@@ -1568,7 +1567,7 @@ static int want_object_in_pack(const struct object_id *oid,
 		*found_offset = 0;
 	}
 
-	for (m = get_multi_pack_index(the_repository); m; m = m->next) {
+	for (struct multi_pack_index *m = get_multi_pack_index(the_repository); m; m = m->next) {
 		struct pack_entry e;
 		if (fill_midx_entry(the_repository, oid, &e, m)) {
 			want = want_object_in_pack_one(e.p, oid, exclude, found_pack, found_offset);
@@ -1718,7 +1717,6 @@ static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
 	void *data;
 	unsigned long size;
 	enum object_type type;
-	int neigh;
 	int my_ix = pbase_tree_cache_ix(oid);
 	int available_ix = -1;
 
@@ -1726,7 +1724,7 @@ static struct pbase_tree_cache *pbase_tree_get(const struct object_id *oid)
 	 * your object will be found at your index or within a few
 	 * slots after that slot if it is cached.
 	 */
-	for (neigh = 0; neigh < 8; neigh++) {
+	for (int neigh = 0; neigh < 8; neigh++) {
 		ent = pbase_tree_cache[my_ix];
 		if (ent && oideq(&ent->oid, oid)) {
 			ent->ref++;
@@ -1872,7 +1870,6 @@ static int check_pbase_path(unsigned hash)
 
 static void add_preferred_base_object(const char *name)
 {
-	struct pbase_tree *it;
 	size_t cmplen;
 	unsigned hash = pack_name_hash(name);
 
@@ -1880,7 +1877,7 @@ static void add_preferred_base_object(const char *name)
 		return;
 
 	cmplen = name_cmp_len(name);
-	for (it = pbase_tree; it; it = it->next) {
+	for (struct pbase_tree *it = pbase_tree; it; it = it->next) {
 		if (cmplen == 0) {
 			add_object_entry(&it->pcache.oid, OBJ_TREE, NULL, 1);
 		}
@@ -1926,7 +1923,6 @@ static void add_preferred_base(struct object_id *oid)
 static void cleanup_preferred_base(void)
 {
 	struct pbase_tree *it;
-	unsigned i;
 
 	it = pbase_tree;
 	pbase_tree = NULL;
@@ -1937,7 +1933,7 @@ static void cleanup_preferred_base(void)
 		free(tmp);
 	}
 
-	for (i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
+	for (unsigned i = 0; i < ARRAY_SIZE(pbase_tree_cache); i++) {
 		if (!pbase_tree_cache[i])
 			continue;
 		free(pbase_tree_cache[i]->tree_data);
@@ -1996,9 +1992,7 @@ static int can_reuse_delta(const struct object_id *base_oid,
 
 static void prefetch_to_pack(uint32_t object_index_start) {
 	struct oid_array to_fetch = OID_ARRAY_INIT;
-	uint32_t i;
-
-	for (i = object_index_start; i < to_pack.nr_objects; i++) {
+	for (uint32_t i = object_index_start; i < to_pack.nr_objects; i++) {
 		struct object_entry *entry = to_pack.objects + i;
 
 		if (!oid_object_info_extended(the_repository,
@@ -2727,7 +2721,7 @@ static unsigned long free_unpacked(struct unpacked *n)
 static void find_deltas(struct object_entry **list, unsigned *list_size,
 			int window, int depth, unsigned *processed)
 {
-	uint32_t i, idx = 0, count = 0;
+	uint32_t idx = 0, count = 0;
 	struct unpacked *array;
 	unsigned long mem_usage = 0;
 
@@ -2859,7 +2853,7 @@ static void find_deltas(struct object_entry **list, unsigned *list_size,
 			idx = 0;
 	}
 
-	for (i = 0; i < window; ++i) {
+	for (uint32_t i = 0; i < window; ++i) {
 		free_delta_index(array[i].index);
 		free(array[i].data);
 	}
@@ -3130,7 +3124,7 @@ static int add_ref_tag(const char *tag UNUSED, const struct object_id *oid,
 static void prepare_pack(int window, int depth)
 {
 	struct object_entry **delta_list;
-	uint32_t i, nr_deltas;
+	uint32_t nr_deltas;
 	unsigned n;
 
 	if (use_delta_islands)
@@ -3154,7 +3148,7 @@ static void prepare_pack(int window, int depth)
 	ALLOC_ARRAY(delta_list, to_pack.nr_objects);
 	nr_deltas = n = 0;
 
-	for (i = 0; i < to_pack.nr_objects; i++) {
+	for (uint32_t i = 0; i < to_pack.nr_objects; i++) {
 		struct object_entry *entry = to_pack.objects + i;
 
 		if (DELTA(entry))
@@ -3630,7 +3624,6 @@ static void enumerate_cruft_objects(void)
 
 static void enumerate_and_traverse_cruft_objects(struct string_list *fresh_packs)
 {
-	struct packed_git *p;
 	struct rev_info revs;
 	int ret;
 
@@ -3658,7 +3651,7 @@ static void enumerate_and_traverse_cruft_objects(struct string_list *fresh_packs
 	 * Re-mark only the fresh packs as kept so that objects in
 	 * unknown packs do not halt the reachability traversal early.
 	 */
-	for (p = get_all_packs(the_repository); p; p = p->next)
+	for (struct packed_git *p = get_all_packs(the_repository); p; p = p->next)
 		p->pack_keep_in_core = 0;
 	mark_pack_kept_in_core(fresh_packs, 1);
 
@@ -3677,7 +3670,6 @@ static void read_cruft_objects(void)
 	struct strbuf buf = STRBUF_INIT;
 	struct string_list discard_packs = STRING_LIST_INIT_DUP;
 	struct string_list fresh_packs = STRING_LIST_INIT_DUP;
-	struct packed_git *p;
 
 	ignore_packed_keep_in_core = 1;
 
@@ -3694,7 +3686,7 @@ static void read_cruft_objects(void)
 	string_list_sort(&discard_packs);
 	string_list_sort(&fresh_packs);
 
-	for (p = get_all_packs(the_repository); p; p = p->next) {
+	for (struct packed_git *p = get_all_packs(the_repository); p; p = p->next) {
 		const char *pack_name = pack_basename(p);
 		struct string_list_item *item;
 
@@ -3781,13 +3773,12 @@ static void show_object(struct object *obj, const char *name,
 	add_object_entry(&obj->oid, obj->type, name, 0);
 
 	if (use_delta_islands) {
-		const char *p;
 		unsigned depth;
 		struct object_entry *ent;
 
 		/* the empty string is a root tree, which is depth 0 */
 		depth = *name ? 1 : 0;
-		for (p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
+		for (const char *p = strchr(name, '/'); p; p = strchr(p + 1, '/'))
 			depth++;
 
 		ent = packlist_find(&to_pack, &obj->oid);
@@ -3981,12 +3972,11 @@ static int loosened_object_can_be_discarded(const struct object_id *oid,
 
 static void loosen_unused_packed_objects(void)
 {
-	struct packed_git *p;
 	uint32_t i;
 	uint32_t loosened_objects_nr = 0;
 	struct object_id oid;
 
-	for (p = get_all_packs(the_repository); p; p = p->next) {
+	for (struct packed_git *p = get_all_packs(the_repository); p; p = p->next) {
 		if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
 			continue;
 
@@ -4183,12 +4173,10 @@ static void get_object_list(struct rev_info *revs, int ac, const char **av)
 
 static void add_extra_kept_packs(const struct string_list *names)
 {
-	struct packed_git *p;
-
 	if (!names->nr)
 		return;
 
-	for (p = get_all_packs(the_repository); p; p = p->next) {
+	for (struct packed_git *p = get_all_packs(the_repository); p; p = p->next) {
 		const char *name = basename(p->pack_name);
 		int i;
 
@@ -4545,14 +4533,7 @@ int cmd_pack_objects(int argc, const char **argv, const char *prefix)
 		if (!p) /* no keep-able packs found */
 			ignore_packed_keep_on_disk = 0;
 	}
-	if (local) {
-		/*
-		 * unlike ignore_packed_keep_on_disk above, we do not
-		 * want to unset "local" based on looking at packs, as
-		 * it also covers non-local objects
-		 */
-		struct packed_git *p;
-		for (p = get_all_packs(the_repository); p; p = p->next) {
+	if (local) {for (struct packed_git *p = get_all_packs(the_repository); p; p = p->next) {
 			if (!p->pack_local) {
 				have_non_local_packs = 1;
 				break;
diff --git a/builtin/pack-redundant.c b/builtin/pack-redundant.c
index 4c735ba069..0891a05692 100644
--- a/builtin/pack-redundant.c
+++ b/builtin/pack-redundant.c
@@ -368,7 +368,6 @@ static int cmp_remaining_objects(const void *a, const void *b)
 static void sort_pack_list(struct pack_list **pl)
 {
 	struct pack_list **ary, *p;
-	int i;
 	size_t n = pack_list_size(*pl);
 
 	if (n < 2)
@@ -382,7 +381,7 @@ static void sort_pack_list(struct pack_list **pl)
 	QSORT(ary, n, cmp_remaining_objects);
 
 	/* link them back again */
-	for (i = 0; i < n - 1; i++)
+	for (int i = 0; i < n - 1; i++)
 		ary[i]->next = ary[i + 1];
 	ary[n - 1]->next = NULL;
 	*pl = ary[0];
diff --git a/builtin/pull.c b/builtin/pull.c
index 73a68b75b0..ff5c73ed1f 100644
--- a/builtin/pull.c
+++ b/builtin/pull.c
@@ -283,10 +283,9 @@ static void argv_push_force(struct strvec *arr)
  */
 static void set_reflog_message(int argc, const char **argv)
 {
-	int i;
 	struct strbuf msg = STRBUF_INIT;
 
-	for (i = 0; i < argc; i++) {
+	for (int i = 0; i < argc; i++) {
 		if (i)
 			strbuf_addch(&msg, ' ');
 		strbuf_addstr(&msg, argv[i]);
@@ -937,11 +936,10 @@ static int get_can_ff(struct object_id *orig_head,
 static int already_up_to_date(struct object_id *orig_head,
 			      struct oid_array *merge_heads)
 {
-	int i;
 	struct commit *ours;
 
 	ours = lookup_commit_reference(the_repository, orig_head);
-	for (i = 0; i < merge_heads->nr; i++) {
+	for (int i = 0; i < merge_heads->nr; i++) {
 		struct commit_list *list = NULL;
 		struct commit *theirs;
 		int ok;
diff --git a/builtin/push.c b/builtin/push.c
index 2fbb31c3ad..2d4e7e329c 100644
--- a/builtin/push.c
+++ b/builtin/push.c
@@ -100,9 +100,7 @@ static void set_refspecs(const char **refs, int nr, const char *repo)
 {
 	struct remote *remote = NULL;
 	struct ref *local_refs = NULL;
-	int i;
-
-	for (i = 0; i < nr; i++) {
+	for (int i = 0; i < nr; i++) {
 		const char *ref = refs[i];
 		if (!strcmp("tag", ref)) {
 			if (nr <= ++i)
diff --git a/builtin/range-diff.c b/builtin/range-diff.c
index f02cbac087..b75283f2f5 100644
--- a/builtin/range-diff.c
+++ b/builtin/range-diff.c
@@ -39,7 +39,7 @@ int cmd_range_diff(int argc, const char **argv, const char *prefix)
 		OPT_END()
 	};
 	struct option *options;
-	int i, dash_dash = -1, res = 0;
+	int dash_dash = -1, res = 0;
 	struct strbuf range1 = STRBUF_INIT, range2 = STRBUF_INIT;
 	struct object_id oid;
 	const char *three_dots = NULL;
@@ -58,7 +58,7 @@ int cmd_range_diff(int argc, const char **argv, const char *prefix)
 	if (!simple_color)
 		diffopt.use_color = 1;
 
-	for (i = 0; i < argc; i++)
+	for (int i = 0; i < argc; i++)
 		if (!strcmp(argv[i], "--")) {
 			dash_dash = i;
 			break;
diff --git a/builtin/read-tree.c b/builtin/read-tree.c
index 20e7db1973..196e87c0cd 100644
--- a/builtin/read-tree.c
+++ b/builtin/read-tree.c
@@ -88,11 +88,9 @@ static void debug_stage(const char *label, const struct cache_entry *ce,
 static int debug_merge(const struct cache_entry * const *stages,
 		       struct unpack_trees_options *o)
 {
-	int i;
-
 	printf("* %d-way merge\n", o->internal.merge_size);
 	debug_stage("index", stages[0], o);
-	for (i = 1; i <= o->internal.merge_size; i++) {
+	for (int i = 1; i <= o->internal.merge_size; i++) {
 		char buf[24];
 		xsnprintf(buf, sizeof(buf), "ent#%d", i);
 		debug_stage(buf, stages[i], o);
diff --git a/builtin/receive-pack.c b/builtin/receive-pack.c
index db65607485..da1ee58688 100644
--- a/builtin/receive-pack.c
+++ b/builtin/receive-pack.c
@@ -413,12 +413,10 @@ static void proc_receive_ref_append(const char *prefix)
 
 static int proc_receive_ref_matches(struct command *cmd)
 {
-	struct proc_receive_ref *p;
-
 	if (!proc_receive_ref)
 		return 0;
 
-	for (p = proc_receive_ref; p; p = p->next) {
+	for (struct proc_receive_ref *p = proc_receive_ref; p; p = p->next) {
 		const char *match = p->ref_prefix;
 		const char *remains;
 
@@ -547,7 +545,6 @@ static void hmac_hash(unsigned char *out,
 	unsigned char key[GIT_MAX_BLKSZ];
 	unsigned char k_ipad[GIT_MAX_BLKSZ];
 	unsigned char k_opad[GIT_MAX_BLKSZ];
-	int i;
 	git_hash_ctx ctx;
 
 	/* RFC 2104 2. (1) */
@@ -561,7 +558,7 @@ static void hmac_hash(unsigned char *out,
 	}
 
 	/* RFC 2104 2. (2) & (5) */
-	for (i = 0; i < sizeof(key); i++) {
+	for (int i = 0; i < sizeof(key); i++) {
 		k_ipad[i] = key[i] ^ 0x36;
 		k_opad[i] = key[i] ^ 0x5c;
 	}
@@ -600,9 +597,7 @@ static char *prepare_push_cert_nonce(const char *path, timestamp_t stamp)
 static int constant_memequal(const char *a, const char *b, size_t n)
 {
 	int res = 0;
-	size_t i;
-
-	for (i = 0; i < n; i++)
+	for (size_t i = 0; i < n; i++)
 		res |= a[i] ^ b[i];
 	return res;
 }
@@ -803,8 +798,7 @@ static int run_and_feed_hook(const char *hook_name, feed_fn feed,
 	proc.trace2_hook_name = hook_name;
 
 	if (feed_state->push_options) {
-		size_t i;
-		for (i = 0; i < feed_state->push_options->nr; i++)
+		for (size_t i = 0; i < feed_state->push_options->nr; i++)
 			strvec_pushf(&proc.env,
 				     "GIT_PUSH_OPTION_%"PRIuMAX"=%s",
 				     (uintmax_t)i,
@@ -958,7 +952,6 @@ static int read_proc_receive_report(struct packet_reader *reader,
 				    struct command *commands,
 				    struct strbuf *errmsg)
 {
-	struct command *cmd;
 	struct command *hint = NULL;
 	struct ref_push_report *report = NULL;
 	int new_report = 0;
@@ -1077,7 +1070,7 @@ static int read_proc_receive_report(struct packet_reader *reader,
 		new_report = 1;
 	}
 
-	for (cmd = commands; cmd; cmd = cmd->next)
+	for (struct command *cmd = commands; cmd; cmd = cmd->next)
 		if (cmd->run_proc_receive && !cmd->error_string &&
 		    !(cmd->run_proc_receive & RUN_PROC_RECEIVE_RETURNED)) {
 		    cmd->error_string = "proc-receive failed to report status";
@@ -1608,7 +1601,6 @@ static const char *update(struct command *cmd, struct shallow_info *si)
 
 static void run_update_post_hook(struct command *commands)
 {
-	struct command *cmd;
 	struct child_process proc = CHILD_PROCESS_INIT;
 	const char *hook;
 
@@ -1616,7 +1608,7 @@ static void run_update_post_hook(struct command *commands)
 	if (!hook)
 		return;
 
-	for (cmd = commands; cmd; cmd = cmd->next) {
+	for (struct command *cmd = commands; cmd; cmd = cmd->next) {
 		if (cmd->error_string || cmd->did_not_exist)
 			continue;
 		if (!proc.args.nr)
@@ -1728,9 +1720,7 @@ static const struct object_id *command_singleton_iterator(void *cb_data)
 static void set_connectivity_errors(struct command *commands,
 				    struct shallow_info *si)
 {
-	struct command *cmd;
-
-	for (cmd = commands; cmd; cmd = cmd->next) {
+	for (struct command *cmd = commands; cmd; cmd = cmd->next) {
 		struct command *singleton = cmd;
 		struct check_connected_options opt = CHECK_CONNECTED_INIT;
 
@@ -1774,12 +1764,11 @@ static void reject_updates_to_hidden(struct command *commands)
 {
 	struct strbuf refname_full = STRBUF_INIT;
 	size_t prefix_len;
-	struct command *cmd;
 
 	strbuf_addstr(&refname_full, get_git_namespace());
 	prefix_len = refname_full.len;
 
-	for (cmd = commands; cmd; cmd = cmd->next) {
+	for (struct command *cmd = commands; cmd; cmd = cmd->next) {
 		if (cmd->error_string)
 			continue;
 
@@ -1805,9 +1794,7 @@ static int should_process_cmd(struct command *cmd)
 static void BUG_if_skipped_connectivity_check(struct command *commands,
 					       struct shallow_info *si)
 {
-	struct command *cmd;
-
-	for (cmd = commands; cmd; cmd = cmd->next) {
+	for (struct command *cmd = commands; cmd; cmd = cmd->next) {
 		if (should_process_cmd(cmd) && si->shallow_ref[cmd->index])
 			bug("connectivity check has not been run on ref %s",
 			    cmd->ref_name);
@@ -1818,10 +1805,9 @@ static void BUG_if_skipped_connectivity_check(struct command *commands,
 static void execute_commands_non_atomic(struct command *commands,
 					struct shallow_info *si)
 {
-	struct command *cmd;
 	struct strbuf err = STRBUF_INIT;
 
-	for (cmd = commands; cmd; cmd = cmd->next) {
+	for (struct command *cmd = commands; cmd; cmd = cmd->next) {
 		if (!should_process_cmd(cmd) || cmd->run_proc_receive)
 			continue;
 
@@ -2392,12 +2378,11 @@ static void update_shallow_info(struct command *commands,
 
 static void report(struct command *commands, const char *unpack_status)
 {
-	struct command *cmd;
 	struct strbuf buf = STRBUF_INIT;
 
 	packet_buf_write(&buf, "unpack %s\n",
 			 unpack_status ? unpack_status : "ok");
-	for (cmd = commands; cmd; cmd = cmd->next) {
+	for (struct command *cmd = commands; cmd; cmd = cmd->next) {
 		if (!cmd->error_string)
 			packet_buf_write(&buf, "ok %s\n",
 					 cmd->ref_name);
@@ -2416,13 +2401,12 @@ static void report(struct command *commands, const char *unpack_status)
 
 static void report_v2(struct command *commands, const char *unpack_status)
 {
-	struct command *cmd;
 	struct strbuf buf = STRBUF_INIT;
 	struct ref_push_report *report;
 
 	packet_buf_write(&buf, "unpack %s\n",
 			 unpack_status ? unpack_status : "ok");
-	for (cmd = commands; cmd; cmd = cmd->next) {
+	for (struct command *cmd = commands; cmd; cmd = cmd->next) {
 		int count = 0;
 
 		if (cmd->error_string) {
@@ -2461,8 +2445,7 @@ static void report_v2(struct command *commands, const char *unpack_status)
 
 static int delete_only(struct command *commands)
 {
-	struct command *cmd;
-	for (cmd = commands; cmd; cmd = cmd->next) {
+	for (struct command *cmd = commands; cmd; cmd = cmd->next) {
 		if (!is_null_oid(&cmd->new_oid))
 			return 0;
 	}
@@ -2551,8 +2534,7 @@ int cmd_receive_pack(int argc, const char **argv, const char *prefix)
 		if (use_push_options)
 			read_push_options(&reader, &push_options);
 		if (!check_cert_push_options(&push_options)) {
-			struct command *cmd;
-			for (cmd = commands; cmd; cmd = cmd->next)
+			for (struct command *cmd = commands; cmd; cmd = cmd->next)
 				cmd->error_string = "inconsistent push options";
 		}
 
diff --git a/builtin/reflog.c b/builtin/reflog.c
index 2c3369fca5..bee26f2998 100644
--- a/builtin/reflog.c
+++ b/builtin/reflog.c
@@ -160,12 +160,10 @@ static int reflog_expire_config(const char *var, const char *value,
 
 static void set_reflog_expiry_param(struct cmd_reflog_expire_cb *cb, const char *ref)
 {
-	struct reflog_expire_cfg *ent;
-
 	if (cb->explicit_expiry == (EXPIRE_TOTAL|EXPIRE_UNREACH))
 		return; /* both given explicitly -- nothing to tweak */
 
-	for (ent = reflog_expire_cfg; ent; ent = ent->next) {
+	for (struct reflog_expire_cfg *ent = reflog_expire_cfg; ent; ent = ent->next) {
 		if (!wildmatch(ent->pattern, ref, 0)) {
 			if (!(cb->explicit_expiry & EXPIRE_TOTAL))
 				cb->expire_total = ent->expire_total;
@@ -242,7 +240,7 @@ static int cmd_reflog_expire(int argc, const char **argv, const char *prefix)
 {
 	struct cmd_reflog_expire_cb cmd = { 0 };
 	timestamp_t now = time(NULL);
-	int i, status, do_all, single_worktree = 0;
+	int status, do_all, single_worktree = 0;
 	unsigned int flags = 0;
 	int verbose = 0;
 	reflog_expiry_should_prune_fn *should_prune_fn = should_expire_reflog_ent;
@@ -313,10 +311,10 @@ static int cmd_reflog_expire(int argc, const char **argv, const char *prefix)
 			.reflogs = STRING_LIST_INIT_DUP,
 		};
 		struct string_list_item *item;
-		struct worktree **worktrees, **p;
+		struct worktree **worktrees;
 
 		worktrees = get_worktrees();
-		for (p = worktrees; *p; p++) {
+		for (struct worktree **p = worktrees; *p; p++) {
 			if (single_worktree && !(*p)->is_current)
 				continue;
 			collected.worktree = *p;
@@ -341,7 +339,7 @@ static int cmd_reflog_expire(int argc, const char **argv, const char *prefix)
 		string_list_clear(&collected.reflogs, 0);
 	}
 
-	for (i = 0; i < argc; i++) {
+	for (int i = 0; i < argc; i++) {
 		char *ref;
 		struct expire_reflog_policy_cb cb = { .cmd = cmd };
 
@@ -362,7 +360,7 @@ static int cmd_reflog_expire(int argc, const char **argv, const char *prefix)
 
 static int cmd_reflog_delete(int argc, const char **argv, const char *prefix)
 {
-	int i, status = 0;
+	int status = 0;
 	unsigned int flags = 0;
 	int verbose = 0;
 
@@ -384,7 +382,7 @@ static int cmd_reflog_delete(int argc, const char **argv, const char *prefix)
 	if (argc < 1)
 		return error(_("no reflog specified to delete"));
 
-	for (i = 0; i < argc; i++)
+	for (int i = 0; i < argc; i++)
 		status |= reflog_delete(argv[i], flags, verbose);
 
 	return status;
diff --git a/builtin/remote.c b/builtin/remote.c
index d91bbe728d..97a33ea644 100644
--- a/builtin/remote.c
+++ b/builtin/remote.c
@@ -366,9 +366,7 @@ static int get_ref_states(const struct ref *remote_refs, struct ref_states *stat
 {
 	struct ref *fetch_map = NULL, **tail = &fetch_map;
 	struct ref *ref, *stale_refs;
-	int i;
-
-	for (i = 0; i < states->remote->fetch.nr; i++)
+	for (int i = 0; i < states->remote->fetch.nr; i++)
 		if (get_fetch_map(remote_refs, &states->remote->fetch.items[i], &tail, 1))
 			die(_("Could not get fetch map for refspec %s"),
 				states->remote->fetch.raw[i]);
@@ -415,7 +413,7 @@ static int get_push_ref_states(const struct ref *remote_refs,
 	struct ref_states *states)
 {
 	struct remote *remote = states->remote;
-	struct ref *ref, *local_refs, *push_map;
+	struct ref *local_refs, *push_map;
 	if (remote->mirror)
 		return 0;
 
@@ -424,7 +422,7 @@ static int get_push_ref_states(const struct ref *remote_refs,
 
 	match_push_refs(local_refs, &push_map, &remote->push, MATCH_REFS_NONE);
 
-	for (ref = push_map; ref; ref = ref->next) {
+	for (struct ref *ref = push_map; ref; ref = ref->next) {
 		struct string_list_item *item;
 		struct push_info *info;
 
@@ -458,7 +456,6 @@ static int get_push_ref_states(const struct ref *remote_refs,
 
 static int get_push_ref_states_noquery(struct ref_states *states)
 {
-	int i;
 	struct remote *remote = states->remote;
 	struct string_list_item *item;
 	struct push_info *info;
@@ -472,7 +469,7 @@ static int get_push_ref_states_noquery(struct ref_states *states)
 		info->status = PUSH_STATUS_NOTQUERIED;
 		info->dest = xstrdup(item->string);
 	}
-	for (i = 0; i < remote->push.nr; i++) {
+	for (int i = 0; i < remote->push.nr; i++) {
 		const struct refspec_item *spec = &remote->push.items[i];
 		if (spec->matching)
 			item = string_list_append(&states->push, _("(matching)"));
@@ -491,7 +488,7 @@ static int get_push_ref_states_noquery(struct ref_states *states)
 
 static int get_head_names(const struct ref *remote_refs, struct ref_states *states)
 {
-	struct ref *ref, *matches;
+	struct ref *matches;
 	struct ref *fetch_map = NULL, **fetch_map_tail = &fetch_map;
 	struct refspec_item refspec;
 
@@ -502,7 +499,7 @@ static int get_head_names(const struct ref *remote_refs, struct ref_states *stat
 	get_fetch_map(remote_refs, &refspec, &fetch_map_tail, 0);
 	matches = guess_remote_head(find_ref_by_name(remote_refs, "HEAD"),
 				    fetch_map, 1);
-	for (ref = matches; ref; ref = ref->next)
+	for (struct ref *ref = matches; ref; ref = ref->next)
 		string_list_append(&states->heads, abbrev_branch(ref->name));
 
 	free_refs(fetch_map);
@@ -548,7 +545,6 @@ static int add_branch_for_removal(const char *refname,
 {
 	struct branches_for_remote *branches = cb_data;
 	struct refspec_item refspec;
-	struct known_remote *kr;
 
 	memset(&refspec, 0, sizeof(refspec));
 	refspec.dst = (char *)refname;
@@ -556,7 +552,7 @@ static int add_branch_for_removal(const char *refname,
 		return 0;
 
 	/* don't delete a branch if another remote also uses it */
-	for (kr = branches->keep->list; kr; kr = kr->next) {
+	for (struct known_remote *kr = branches->keep->list; kr; kr = kr->next) {
 		memset(&refspec, 0, sizeof(refspec));
 		refspec.dst = (char *)refname;
 		if (!remote_find_tracking(kr->remote, &refspec))
@@ -1097,7 +1093,6 @@ static int show_local_info_item(struct string_list_item *item, void *cb_data)
 	struct branch_info *branch_info = item->util;
 	struct string_list *merge = &branch_info->merge;
 	int width = show_info->width + 4;
-	int i;
 
 	if (branch_info->rebase >= REBASE_TRUE && branch_info->merge.nr > 1) {
 		error(_("invalid branch.%s.merge; cannot rebase onto > 1 branch"),
@@ -1123,7 +1118,7 @@ static int show_local_info_item(struct string_list_item *item, void *cb_data)
 	} else {
 		printf_ln(_("merges with remote %s"), merge->items[0].string);
 	}
-	for (i = 1; i < merge->nr; i++)
+	for (int i = 1; i < merge->nr; i++)
 		printf(_("%-*s    and with remote %s\n"), width, "",
 		       merge->items[i].string);
 
@@ -1208,7 +1203,7 @@ static int get_one_entry(struct remote *remote, void *priv)
 	struct string_list *list = priv;
 	struct strbuf remote_info_buf = STRBUF_INIT;
 	const char **url;
-	int i, url_nr;
+	int url_nr;
 
 	if (remote->url_nr > 0) {
 		struct strbuf promisor_config = STRBUF_INIT;
@@ -1231,7 +1226,7 @@ static int get_one_entry(struct remote *remote, void *priv)
 		url = remote->url;
 		url_nr = remote->url_nr;
 	}
-	for (i = 0; i < url_nr; i++)
+	for (int i = 0; i < url_nr; i++)
 	{
 		strbuf_addf(&remote_info_buf, "%s (push)", url[i]);
 		string_list_append(list, remote->name)->util =
@@ -1249,10 +1244,8 @@ static int show_all(void)
 	result = for_each_remote(get_one_entry, &list);
 
 	if (!result) {
-		int i;
-
 		string_list_sort(&list);
-		for (i = 0; i < list.nr; i++) {
+		for (int i = 0; i < list.nr; i++) {
 			struct string_list_item *item = list.items + i;
 			if (verbose)
 				printf("%s\t%s\n", item->string,
@@ -1510,7 +1503,7 @@ static int get_remote_default(const char *key, const char *value UNUSED,
 
 static int update(int argc, const char **argv, const char *prefix)
 {
-	int i, prune = -1;
+	int prune = -1;
 	struct option options[] = {
 		OPT_BOOL('p', "prune", &prune,
 			 N_("prune remotes after fetching")),
@@ -1532,7 +1525,7 @@ static int update(int argc, const char **argv, const char *prefix)
 	strvec_push(&cmd.args, "--multiple");
 	if (argc < 2)
 		strvec_push(&cmd.args, "default");
-	for (i = 1; i < argc; i++)
+	for (int i = 1; i < argc; i++)
 		strvec_push(&cmd.args, argv[i]);
 
 	if (strcmp(cmd.args.v[cmd.args.nr-1], "default") == 0) {
@@ -1665,7 +1658,7 @@ static int get_url(int argc, const char **argv, const char *prefix)
 
 static int set_url(int argc, const char **argv, const char *prefix)
 {
-	int i, push_mode = 0, add_mode = 0, delete_mode = 0;
+	int push_mode = 0, add_mode = 0, delete_mode = 0;
 	int matches = 0, negative_matches = 0;
 	const char *remotename = NULL;
 	const char *newurl = NULL;
@@ -1732,7 +1725,7 @@ static int set_url(int argc, const char **argv, const char *prefix)
 	if (regcomp(&old_regex, oldurl, REG_EXTENDED))
 		die(_("Invalid old URL pattern: %s"), oldurl);
 
-	for (i = 0; i < urlset_nr; i++)
+	for (int i = 0; i < urlset_nr; i++)
 		if (!regexec(&old_regex, urlset[i], 0, NULL, 0))
 			matches++;
 		else
diff --git a/builtin/repack.c b/builtin/repack.c
index ede36328a3..197af23c55 100644
--- a/builtin/repack.c
+++ b/builtin/repack.c
@@ -235,10 +235,9 @@ static void existing_packs_release(struct existing_packs *existing)
 static void collect_pack_filenames(struct existing_packs *existing,
 				   const struct string_list *extra_keep)
 {
-	struct packed_git *p;
 	struct strbuf buf = STRBUF_INIT;
 
-	for (p = get_all_packs(the_repository); p; p = p->next) {
+	for (struct packed_git *p = get_all_packs(the_repository); p; p = p->next) {
 		int i;
 		const char *base;
 
@@ -340,9 +339,7 @@ static struct generated_pack_data *populate_pack_exts(const char *name)
 	struct stat statbuf;
 	struct strbuf path = STRBUF_INIT;
 	struct generated_pack_data *data = xcalloc(1, sizeof(*data));
-	int i;
-
-	for (i = 0; i < ARRAY_SIZE(exts); i++) {
+	for (int i = 0; i < ARRAY_SIZE(exts); i++) {
 		strbuf_reset(&path);
 		strbuf_addf(&path, "%s-%s%s", packtmp, name, exts[i].name);
 
@@ -359,8 +356,7 @@ static struct generated_pack_data *populate_pack_exts(const char *name)
 static int has_pack_ext(const struct generated_pack_data *data,
 			const char *ext)
 {
-	int i;
-	for (i = 0; i < ARRAY_SIZE(exts); i++) {
+	for (int i = 0; i < ARRAY_SIZE(exts); i++) {
 		if (strcmp(exts[i].name, ext))
 			continue;
 		return !!data->tempfiles[i];
@@ -460,10 +456,9 @@ static void init_pack_geometry(struct pack_geometry *geometry,
 			       struct existing_packs *existing,
 			       const struct pack_objects_args *args)
 {
-	struct packed_git *p;
 	struct strbuf buf = STRBUF_INIT;
 
-	for (p = get_all_packs(the_repository); p; p = p->next) {
+	for (struct packed_git *p = get_all_packs(the_repository); p; p = p->next) {
 		if (args->local && !p->pack_local)
 			/*
 			 * When asked to only repack local packfiles we skip
@@ -592,8 +587,6 @@ static void split_pack_geometry(struct pack_geometry *geometry)
 
 static struct packed_git *get_preferred_pack(struct pack_geometry *geometry)
 {
-	uint32_t i;
-
 	if (!geometry) {
 		/*
 		 * No geometry means either an all-into-one repack (in which
@@ -614,7 +607,7 @@ static struct packed_git *get_preferred_pack(struct pack_geometry *geometry)
 	 * other words, it is the largest pack that does not get rolled up in
 	 * the geometric repack.
 	 */
-	for (i = geometry->pack_nr; i > geometry->split; i--)
+	for (uint32_t i = geometry->pack_nr; i > geometry->split; i--)
 		/*
 		 * A pack that is not local would never be included in a
 		 * multi-pack index. We thus skip over any non-local packs.
@@ -630,9 +623,7 @@ static void geometry_remove_redundant_packs(struct pack_geometry *geometry,
 					    struct existing_packs *existing)
 {
 	struct strbuf buf = STRBUF_INIT;
-	uint32_t i;
-
-	for (i = 0; i < geometry->split; i++) {
+	for (uint32_t i = 0; i < geometry->split; i++) {
 		struct packed_git *p = geometry->pack[i];
 		if (string_list_has_string(names, hash_to_hex(p->hash)))
 			continue;
@@ -734,8 +725,7 @@ static void midx_included_packs(struct string_list *include,
 		string_list_insert(include, xstrfmt("pack-%s.idx", item->string));
 	if (geometry->split_factor) {
 		struct strbuf buf = STRBUF_INIT;
-		uint32_t i;
-		for (i = geometry->split; i < geometry->pack_nr; i++) {
+		for (uint32_t i = geometry->split; i < geometry->pack_nr; i++) {
 			struct packed_git *p = geometry->pack[i];
 
 			/*
diff --git a/builtin/replace.c b/builtin/replace.c
index da59600ad2..79f2c1c337 100644
--- a/builtin/replace.c
+++ b/builtin/replace.c
@@ -109,7 +109,7 @@ typedef int (*each_replace_name_fn)(const char *name, const char *ref,
 
 static int for_each_replace_name(const char **argv, each_replace_name_fn fn)
 {
-	const char **p, *full_hex;
+	const char *full_hex;
 	struct strbuf ref = STRBUF_INIT;
 	size_t base_len;
 	int had_error = 0;
@@ -119,7 +119,7 @@ static int for_each_replace_name(const char **argv, each_replace_name_fn fn)
 	strbuf_addstr(&ref, git_replace_ref_base);
 	base_len = ref.len;
 
-	for (p = argv; *p; p++) {
+	for (const char **p = argv; *p; p++) {
 		if (repo_get_oid(the_repository, *p, &oid)) {
 			error("failed to resolve '%s' as a valid ref", *p);
 			had_error = 1;
@@ -367,7 +367,6 @@ static int replace_parents(struct strbuf *buf, int argc, const char **argv)
 {
 	struct strbuf new_parents = STRBUF_INIT;
 	const char *parent_start, *parent_end;
-	int i;
 	const unsigned hexsz = the_hash_algo->hexsz;
 
 	/* find existing parents */
@@ -379,7 +378,7 @@ static int replace_parents(struct strbuf *buf, int argc, const char **argv)
 		parent_end += hexsz + 8; /* "parent " + "hex sha1" + "\n" */
 
 	/* prepare new parents */
-	for (i = 0; i < argc; i++) {
+	for (int i = 0; i < argc; i++) {
 		struct object_id oid;
 		struct commit *commit;
 
@@ -417,7 +416,6 @@ static int check_one_mergetag(struct commit *commit UNUSED,
 	const char *ref = mergetag_data->argv[0];
 	struct object_id tag_oid;
 	struct tag *tag;
-	int i;
 
 	hash_object_file(the_hash_algo, extra->value, extra->len,
 			 OBJ_TAG, &tag_oid);
@@ -428,7 +426,7 @@ static int check_one_mergetag(struct commit *commit UNUSED,
 		return error(_("malformed mergetag in commit '%s'"), ref);
 
 	/* iterate over new parents */
-	for (i = 1; i < mergetag_data->argc; i++) {
+	for (int i = 1; i < mergetag_data->argc; i++) {
 		struct object_id oid;
 		if (repo_get_oid(the_repository, mergetag_data->argv[i], &oid) < 0)
 			return error(_("not a valid object name: '%s'"),
diff --git a/builtin/replay.c b/builtin/replay.c
index 6bc4b47f09..624636cc6e 100644
--- a/builtin/replay.c
+++ b/builtin/replay.c
@@ -94,8 +94,6 @@ struct ref_info {
 static void get_ref_information(struct rev_cmdline_info *cmd_info,
 				struct ref_info *ref_info)
 {
-	int i;
-
 	ref_info->onto = NULL;
 	strset_init(&ref_info->positive_refs);
 	strset_init(&ref_info->negative_refs);
@@ -117,7 +115,7 @@ static void get_ref_information(struct rev_cmdline_info *cmd_info,
 	 * the second because they'd likely just be replaying commits on top
 	 * of the same commit and not making any difference.
 	 */
-	for (i = 0; i < cmd_info->nr; i++) {
+	for (int i = 0; i < cmd_info->nr; i++) {
 		struct rev_cmdline_entry *e = cmd_info->rev + i;
 		struct object_id oid;
 		const char *refexpr = e->name;
diff --git a/builtin/rerere.c b/builtin/rerere.c
index b2efc6f640..29cf9d17d2 100644
--- a/builtin/rerere.c
+++ b/builtin/rerere.c
@@ -16,8 +16,7 @@ static const char * const rerere_usage[] = {
 
 static int outf(void *dummy UNUSED, mmbuffer_t *ptr, int nbuf)
 {
-	int i;
-	for (i = 0; i < nbuf; i++)
+	for (int i = 0; i < nbuf; i++)
 		if (write_in_full(1, ptr[i].ptr, ptr[i].size) < 0)
 			return -1;
 	return 0;
diff --git a/builtin/reset.c b/builtin/reset.c
index f0bf29a478..b654c00511 100644
--- a/builtin/reset.c
+++ b/builtin/reset.c
@@ -58,7 +58,7 @@ static inline int is_merge(void)
 
 static int reset_index(const char *ref, const struct object_id *oid, int reset_type, int quiet)
 {
-	int i, nr = 0;
+	int nr = 0;
 	struct tree_desc desc[2];
 	struct tree *tree;
 	struct unpack_trees_options opts;
@@ -122,7 +122,7 @@ static int reset_index(const char *ref, const struct object_id *oid, int reset_t
 	ret = 0;
 
 out:
-	for (i = 0; i < nr; i++)
+	for (int i = 0; i < nr; i++)
 		free((void *)desc[i].buffer);
 	return ret;
 }
@@ -145,10 +145,9 @@ static void update_index_from_diff(struct diff_queue_struct *q,
 				   struct diff_options *opt UNUSED,
 				   void *data)
 {
-	int i;
 	int intent_to_add = *(int *)data;
 
-	for (i = 0; i < q->nr; i++) {
+	for (int i = 0; i < q->nr; i++) {
 		int pos;
 		struct diff_filespec *one = q->queue[i]->one;
 		int is_in_reset_tree = one->mode && !is_null_oid(&one->oid);
diff --git a/builtin/rev-list.c b/builtin/rev-list.c
index b3f4783858..0aa0320756 100644
--- a/builtin/rev-list.c
+++ b/builtin/rev-list.c
@@ -742,12 +742,11 @@ int cmd_rev_list(int argc, const char **argv, const char *prefix)
 	}
 
 	if (filter_provided_objects) {
-		struct commit_list *c;
 		for (i = 0; i < revs.pending.nr; i++) {
 			struct object_array_entry *pending = revs.pending.objects + i;
 			pending->item->flags |= NOT_USER_GIVEN;
 		}
-		for (c = revs.commits; c; c = c->next)
+		for (struct commit_list *c = revs.commits; c; c = c->next)
 			c->item->object.flags |= NOT_USER_GIVEN;
 	}
 
diff --git a/builtin/rm.c b/builtin/rm.c
index fd130cea2d..fe2c0c5b7b 100644
--- a/builtin/rm.c
+++ b/builtin/rm.c
@@ -55,11 +55,10 @@ static void print_error_files(struct string_list *files_list,
 			      int *errs)
 {
 	if (files_list->nr) {
-		int i;
 		struct strbuf err_msg = STRBUF_INIT;
 
 		strbuf_addstr(&err_msg, main_msg);
-		for (i = 0; i < files_list->nr; i++)
+		for (int i = 0; i < files_list->nr; i++)
 			strbuf_addf(&err_msg,
 				    "\n    %s",
 				    files_list->items[i].string);
@@ -72,8 +71,7 @@ static void print_error_files(struct string_list *files_list,
 
 static void submodules_absorb_gitdir_if_needed(void)
 {
-	int i;
-	for (i = 0; i < list.nr; i++) {
+	for (int i = 0; i < list.nr; i++) {
 		const char *name = list.entry[i].name;
 		int pos;
 		const struct cache_entry *ce;
@@ -105,14 +103,14 @@ static int check_local_mod(struct object_id *head, int index_only)
 	 * lazy, and who cares if removal of files is a tad
 	 * slower than the theoretical maximum speed?
 	 */
-	int i, no_head;
+	int no_head;
 	int errs = 0;
 	struct string_list files_staged = STRING_LIST_INIT_NODUP;
 	struct string_list files_cached = STRING_LIST_INIT_NODUP;
 	struct string_list files_local = STRING_LIST_INIT_NODUP;
 
 	no_head = is_null_oid(head);
-	for (i = 0; i < list.nr; i++) {
+	for (int i = 0; i < list.nr; i++) {
 		struct stat st;
 		int pos;
 		const struct cache_entry *ce;
diff --git a/builtin/send-pack.c b/builtin/send-pack.c
index 3df9eaad09..30ea49318f 100644
--- a/builtin/send-pack.c
+++ b/builtin/send-pack.c
@@ -327,8 +327,7 @@ int cmd_send_pack(int argc, const char **argv, const char *prefix)
 		transport_print_push_status(dest, remote_refs, args.verbose, 0, &reject_reasons);
 
 	if (!args.dry_run && remote) {
-		struct ref *ref;
-		for (ref = remote_refs; ref; ref = ref->next)
+		for (struct ref *ref = remote_refs; ref; ref = ref->next)
 			transport_update_tracking_ref(remote, ref, args.verbose);
 	}
 
diff --git a/builtin/shortlog.c b/builtin/shortlog.c
index 1307ed2b88..cf25851837 100644
--- a/builtin/shortlog.c
+++ b/builtin/shortlog.c
@@ -478,13 +478,13 @@ static void add_wrapped_shortlog_msg(struct strbuf *sb, const char *s,
 
 void shortlog_output(struct shortlog *log)
 {
-	size_t i, j;
+	size_t j;
 	struct strbuf sb = STRBUF_INIT;
 
 	if (log->sort_by_number)
 		STABLE_QSORT(log->list.items, log->list.nr,
 		      log->summary ? compare_by_counter : compare_by_list);
-	for (i = 0; i < log->list.nr; i++) {
+	for (size_t i = 0; i < log->list.nr; i++) {
 		const struct string_list_item *item = &log->list.items[i];
 		if (log->summary) {
 			fprintf(log->file, "%6d\t%s\n",
diff --git a/builtin/show-branch.c b/builtin/show-branch.c
index b01ec761d2..cd9ba4db63 100644
--- a/builtin/show-branch.c
+++ b/builtin/show-branch.c
@@ -523,9 +523,7 @@ static int show_independent(struct commit **rev,
 			    int num_rev,
 			    unsigned int *rev_mask)
 {
-	int i;
-
-	for (i = 0; i < num_rev; i++) {
+	for (int i = 0; i < num_rev; i++) {
 		struct commit *commit = rev[i];
 		unsigned int flag = rev_mask[i];
 
diff --git a/builtin/sparse-checkout.c b/builtin/sparse-checkout.c
index 0f52e25249..15460f153f 100644
--- a/builtin/sparse-checkout.c
+++ b/builtin/sparse-checkout.c
@@ -26,9 +26,7 @@ static char const * const builtin_sparse_checkout_usage[] = {
 
 static void write_patterns_to_file(FILE *fp, struct pattern_list *pl)
 {
-	int i;
-
-	for (i = 0; i < pl->nr; i++) {
+	for (int i = 0; i < pl->nr; i++) {
 		struct path_pattern *p = pl->patterns[i];
 
 		if (p->flags & PATTERN_FLAG_NEGATIVE)
@@ -79,7 +77,6 @@ static int sparse_checkout_list(int argc, const char **argv, const char *prefix)
 	}
 
 	if (pl.use_cone_patterns) {
-		int i;
 		struct pattern_entry *pe;
 		struct hashmap_iter iter;
 		struct string_list sl = STRING_LIST_INIT_DUP;
@@ -91,7 +88,7 @@ static int sparse_checkout_list(int argc, const char **argv, const char *prefix)
 
 		string_list_sort(&sl);
 
-		for (i = 0; i < sl.nr; i++) {
+		for (int i = 0; i < sl.nr; i++) {
 			quote_c_style(sl.items[i].string, NULL, stdout, 0);
 			printf("\n");
 		}
@@ -107,7 +104,7 @@ static int sparse_checkout_list(int argc, const char **argv, const char *prefix)
 
 static void clean_tracked_sparse_directories(struct repository *r)
 {
-	int i, was_full = 0;
+	int was_full = 0;
 	struct strbuf path = STRBUF_INIT;
 	size_t pathlen;
 	struct string_list_item *item;
@@ -150,7 +147,7 @@ static void clean_tracked_sparse_directories(struct repository *r)
 	 * store the entries in a list before exploring, since that might
 	 * expand the sparse-index again.
 	 */
-	for (i = 0; i < r->index->cache_nr; i++) {
+	for (int i = 0; i < r->index->cache_nr; i++) {
 		struct cache_entry *ce = r->index->cache[i];
 
 		if (S_ISSPARSEDIR(ce->ce_mode) &&
diff --git a/builtin/stash.c b/builtin/stash.c
index 7fb355bff0..0bedbe485d 100644
--- a/builtin/stash.c
+++ b/builtin/stash.c
@@ -179,10 +179,9 @@ static int get_stash_info(struct stash_info *info, int argc, const char **argv)
 	struct strbuf symbolic = STRBUF_INIT;
 
 	if (argc > 1) {
-		int i;
 		struct strbuf refs_msg = STRBUF_INIT;
 
-		for (i = 0; i < argc; i++)
+		for (int i = 0; i < argc; i++)
 			strbuf_addf(&refs_msg, " '%s'", argv[i]);
 
 		fprintf_ln(stderr, _("Too many revisions specified:%s"),
@@ -364,9 +363,7 @@ static void add_diff_to_buf(struct diff_queue_struct *q,
 			    struct diff_options *options UNUSED,
 			    void *data)
 {
-	int i;
-
-	for (i = 0; i < q->nr; i++) {
+	for (int i = 0; i < q->nr; i++) {
 		if (is_path_a_directory(q->queue[i]->one->path))
 			continue;
 
@@ -424,7 +421,6 @@ static void unstage_changes_unless_new(struct object_id *orig_tree)
 	struct checkout state = CHECKOUT_INIT;
 	struct diff_options diff_opts;
 	struct lock_file lock = LOCK_INIT;
-	int i;
 
 	/* If any entries have skip_worktree set, we'll have to check 'em out */
 	state.force = 1;
@@ -447,7 +443,7 @@ static void unstage_changes_unless_new(struct object_id *orig_tree)
 	diffcore_std(&diff_opts);
 
 	/* Iterate over the paths that changed due to the merge... */
-	for (i = 0; i < diff_queued_diff.nr; i++) {
+	for (int i = 0; i < diff_queued_diff.nr; i++) {
 		struct diff_filepair *p;
 		struct cache_entry *ce;
 		int pos;
@@ -864,9 +860,7 @@ static void diff_include_untracked(const struct stash_info *info, struct diff_op
 	struct tree *tree[ARRAY_SIZE(oid)];
 	struct tree_desc tree_desc[ARRAY_SIZE(oid)];
 	struct unpack_trees_options unpack_tree_opt = { 0 };
-	int i;
-
-	for (i = 0; i < ARRAY_SIZE(oid); i++) {
+	for (int i = 0; i < ARRAY_SIZE(oid); i++) {
 		tree[i] = parse_tree_indirect(oid[i]);
 		if (parse_tree(tree[i]) < 0)
 			die(_("failed to parse tree"));
@@ -887,7 +881,6 @@ static void diff_include_untracked(const struct stash_info *info, struct diff_op
 
 static int show_stash(int argc, const char **argv, const char *prefix)
 {
-	int i;
 	int ret = -1;
 	struct stash_info info = STASH_INFO_INIT;
 	struct rev_info rev;
@@ -918,7 +911,7 @@ static int show_stash(int argc, const char **argv, const char *prefix)
 			     PARSE_OPT_KEEP_DASHDASH);
 
 	strvec_push(&revision_args, argv[0]);
-	for (i = 1; i < argc; i++) {
+	for (int i = 1; i < argc; i++) {
 		if (argv[i][0] != '-')
 			strvec_push(&stash_args, argv[i]);
 		else
@@ -1049,9 +1042,7 @@ static int store_stash(int argc, const char **argv, const char *prefix)
 
 static void add_pathspecs(struct strvec *args,
 			  const struct pathspec *ps) {
-	int i;
-
-	for (i = 0; i < ps->nr; i++)
+	for (int i = 0; i < ps->nr; i++)
 		strvec_push(args, ps->items[i].original);
 }
 
@@ -1065,7 +1056,6 @@ static void add_pathspecs(struct strvec *args,
 static int get_untracked_files(const struct pathspec *ps, int include_untracked,
 			       struct strbuf *untracked_files)
 {
-	int i;
 	int found = 0;
 	struct dir_struct dir = DIR_INIT;
 
@@ -1073,7 +1063,7 @@ static int get_untracked_files(const struct pathspec *ps, int include_untracked,
 		setup_standard_excludes(&dir);
 
 	fill_directory(&dir, the_repository->index, ps);
-	for (i = 0; i < dir.nr; i++) {
+	for (int i = 0; i < dir.nr; i++) {
 		struct dir_entry *ent = dir.entries[i];
 		found++;
 		strbuf_addstr(untracked_files, ent->name);
@@ -1535,12 +1525,11 @@ static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int q
 
 	repo_read_index_preload(the_repository, NULL, 0);
 	if (!include_untracked && ps->nr) {
-		int i;
 		char *ps_matched = xcalloc(ps->nr, 1);
 
 		/* TODO: audit for interaction with sparse-index. */
 		ensure_full_index(&the_index);
-		for (i = 0; i < the_index.cache_nr; i++)
+		for (int i = 0; i < the_index.cache_nr; i++)
 			ce_path_match(&the_index, the_index.cache[i], ps,
 				      ps_matched);
 
diff --git a/builtin/submodule--helper.c b/builtin/submodule--helper.c
index fda50f2af1..711a184b62 100644
--- a/builtin/submodule--helper.c
+++ b/builtin/submodule--helper.c
@@ -143,7 +143,6 @@ static char *get_submodule_displaypath(const char *path, const char *prefix,
 static char *compute_rev_name(const char *sub_path, const char* object_id)
 {
 	struct strbuf sb = STRBUF_INIT;
-	const char ***d;
 
 	static const char *describe_bare[] = { NULL };
 
@@ -157,7 +156,7 @@ static char *compute_rev_name(const char *sub_path, const char* object_id)
 						describe_contains,
 						describe_all_always, NULL };
 
-	for (d = describe_argv; *d; d++) {
+	for (const char ***d = describe_argv; *d; d++) {
 		struct child_process cp = CHILD_PROCESS_INIT;
 		prepare_submodule_repo_env(&cp.env);
 		cp.dir = sub_path;
@@ -194,7 +193,7 @@ static int module_list_compute(const char **argv,
 			       struct pathspec *pathspec,
 			       struct module_list *list)
 {
-	int i, result = 0;
+	int result = 0;
 	char *ps_matched = NULL;
 
 	parse_pathspec(pathspec, 0,
@@ -207,7 +206,7 @@ static int module_list_compute(const char **argv,
 	if (repo_read_index(the_repository) < 0)
 		die(_("index file corrupt"));
 
-	for (i = 0; i < the_index.cache_nr; i++) {
+	for (int i = 0; i < the_index.cache_nr; i++) {
 		const struct cache_entry *ce = the_index.cache[i];
 
 		if (!match_pathspec(&the_index, pathspec, ce->name, ce_namelen(ce),
@@ -236,10 +235,9 @@ static int module_list_compute(const char **argv,
 
 static void module_list_active(struct module_list *list)
 {
-	int i;
 	struct module_list active_modules = MODULE_LIST_INIT;
 
-	for (i = 0; i < list->nr; i++) {
+	for (int i = 0; i < list->nr; i++) {
 		const struct cache_entry *ce = list->entries[i];
 
 		if (!is_submodule_active(the_repository, ce->name))
@@ -257,10 +255,9 @@ static void module_list_active(struct module_list *list)
 
 static char *get_up_path(const char *path)
 {
-	int i;
 	struct strbuf sb = STRBUF_INIT;
 
-	for (i = count_slashes(path); i; i--)
+	for (int i = count_slashes(path); i; i--)
 		strbuf_addstr(&sb, "../");
 
 	/*
@@ -277,9 +274,7 @@ static char *get_up_path(const char *path)
 static void for_each_listed_submodule(const struct module_list *list,
 				      each_submodule_fn fn, void *cb_data)
 {
-	int i;
-
-	for (i = 0; i < list->nr; i++)
+	for (int i = 0; i < list->nr; i++)
 		fn(list->entries[i], cb_data);
 }
 
@@ -787,9 +782,7 @@ struct module_cb_list {
 
 static void module_cb_list_release(struct module_cb_list *mcbl)
 {
-	int i;
-
-	for (i = 0; i < mcbl->nr; i++) {
+	for (int i = 0; i < mcbl->nr; i++) {
 		struct module_cb *mcb = mcbl->entries[i];
 
 		module_cb_release(mcb);
@@ -1021,8 +1014,7 @@ static void generate_submodule_summary(struct summary_cb *info,
 static void prepare_submodule_summary(struct summary_cb *info,
 				      struct module_cb_list *list)
 {
-	int i;
-	for (i = 0; i < list->nr; i++) {
+	for (int i = 0; i < list->nr; i++) {
 		const struct submodule *sub;
 		struct module_cb *p = list->entries[i];
 		struct strbuf sm_gitdir = STRBUF_INIT;
@@ -1063,9 +1055,8 @@ static void submodule_summary_callback(struct diff_queue_struct *q,
 				       struct diff_options *options UNUSED,
 				       void *data)
 {
-	int i;
 	struct module_cb_list *list = data;
-	for (i = 0; i < q->nr; i++) {
+	for (int i = 0; i < q->nr; i++) {
 		struct diff_filepair *p = q->queue[i];
 		struct module_cb *temp;
 
@@ -2592,7 +2583,7 @@ static int update_submodule(struct update_data *update_data)
 
 static int update_submodules(struct update_data *update_data)
 {
-	int i, ret = 0;
+	int ret = 0;
 	struct submodule_update_clone suc = SUBMODULE_UPDATE_CLONE_INIT;
 	const struct run_process_parallel_opts opts = {
 		.tr2_category = "submodule",
@@ -2622,7 +2613,7 @@ static int update_submodules(struct update_data *update_data)
 		goto cleanup;
 	}
 
-	for (i = 0; i < suc.update_clone_nr; i++) {
+	for (int i = 0; i < suc.update_clone_nr; i++) {
 		struct update_clone_data ucd = suc.update_clone[i];
 		int code;
 
@@ -2812,13 +2803,12 @@ static int push_check(int argc, const char **argv, const char *prefix UNUSED)
 
 	/* Check the refspec */
 	if (argc > 2) {
-		int i;
 		struct ref *local_refs = get_local_heads();
 		struct refspec refspec = REFSPEC_INIT_PUSH;
 
 		refspec_appendn(&refspec, argv + 2, argc - 2);
 
-		for (i = 0; i < refspec.nr; i++) {
+		for (int i = 0; i < refspec.nr; i++) {
 			const struct refspec_item *rs = &refspec.items[i];
 
 			if (rs->pattern || rs->matching)
@@ -2855,7 +2845,6 @@ static int push_check(int argc, const char **argv, const char *prefix UNUSED)
 
 static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
 {
-	int i;
 	struct pathspec pathspec = { 0 };
 	struct module_list list = MODULE_LIST_INIT;
 	const char *super_prefix = NULL;
@@ -2875,7 +2864,7 @@ static int absorb_git_dirs(int argc, const char **argv, const char *prefix)
 	if (module_list_compute(argv, prefix, &pathspec, &list) < 0)
 		goto cleanup;
 
-	for (i = 0; i < list.nr; i++)
+	for (int i = 0; i < list.nr; i++)
 		absorb_git_dir_into_superproject(list.entries[i]->name,
 						 super_prefix);
 
@@ -3239,7 +3228,6 @@ static void die_on_index_match(const char *path, int force)
 		die(_("index file corrupt"));
 
 	if (ps.nr) {
-		int i;
 		char *ps_matched = xcalloc(ps.nr, 1);
 
 		/* TODO: audit for interaction with sparse-index. */
@@ -3249,7 +3237,7 @@ static void die_on_index_match(const char *path, int force)
 		 * Since there is only one pathspec, we just need to
 		 * check ps_matched[0] to know if a cache entry matched.
 		 */
-		for (i = 0; i < the_index.cache_nr; i++) {
+		for (int i = 0; i < the_index.cache_nr; i++) {
 			ce_path_match(&the_index, the_index.cache[i], &ps,
 				      ps_matched);
 
diff --git a/builtin/tag.c b/builtin/tag.c
index 37473ac21f..2e2b315183 100644
--- a/builtin/tag.c
+++ b/builtin/tag.c
@@ -78,12 +78,11 @@ typedef int (*each_tag_name_fn)(const char *name, const char *ref,
 static int for_each_tag_name(const char **argv, each_tag_name_fn fn,
 			     void *cb_data)
 {
-	const char **p;
 	struct strbuf ref = STRBUF_INIT;
 	int had_error = 0;
 	struct object_id oid;
 
-	for (p = argv; *p; p++) {
+	for (const char **p = argv; *p; p++) {
 		strbuf_reset(&ref);
 		strbuf_addf(&ref, "refs/tags/%s", *p);
 		if (read_ref(ref.buf, &oid)) {
diff --git a/builtin/unpack-objects.c b/builtin/unpack-objects.c
index e0a701f2b3..0801d13b0e 100644
--- a/builtin/unpack-objects.c
+++ b/builtin/unpack-objects.c
@@ -248,8 +248,7 @@ static int check_object(struct object *obj, enum object_type type,
 
 static void write_rest(void)
 {
-	unsigned i;
-	for (i = 0; i < nr_objects; i++) {
+	for (unsigned i = 0; i < nr_objects; i++) {
 		if (obj_list[i].obj)
 			check_object(obj_list[i].obj, OBJ_ANY, NULL, NULL);
 	}
@@ -574,7 +573,6 @@ static void unpack_one(unsigned nr)
 
 static void unpack_all(void)
 {
-	int i;
 	struct pack_header *hdr = fill(sizeof(struct pack_header));
 
 	nr_objects = ntohl(hdr->hdr_entries);
@@ -590,7 +588,7 @@ static void unpack_all(void)
 		progress = start_progress(_("Unpacking objects"), nr_objects);
 	CALLOC_ARRAY(obj_list, nr_objects);
 	begin_odb_transaction();
-	for (i = 0; i < nr_objects; i++) {
+	for (int i = 0; i < nr_objects; i++) {
 		unpack_one(i);
 		display_progress(progress, i + 1);
 	}
@@ -603,7 +601,6 @@ static void unpack_all(void)
 
 int cmd_unpack_objects(int argc, const char **argv, const char *prefix UNUSED)
 {
-	int i;
 	struct object_id oid;
 	git_hash_ctx tmp_ctx;
 
@@ -613,7 +610,7 @@ int cmd_unpack_objects(int argc, const char **argv, const char *prefix UNUSED)
 
 	quiet = !isatty(2);
 
-	for (i = 1 ; i < argc; i++) {
+	for (int i = 1; i < argc; i++) {
 		const char *arg = argv[i];
 
 		if (*arg == '-') {
diff --git a/builtin/update-index.c b/builtin/update-index.c
index 7bcaa1476c..60e346960e 100644
--- a/builtin/update-index.c
+++ b/builtin/update-index.c
@@ -655,10 +655,9 @@ static int unresolve_one(const char *path)
 static int do_unresolve(int ac, const char **av,
 			const char *prefix, int prefix_length)
 {
-	int i;
 	int err = 0;
 
-	for (i = 1; i < ac; i++) {
+	for (int i = 1; i < ac; i++) {
 		const char *arg = av[i];
 		char *p = prefix_path(prefix, prefix_length, arg);
 		err |= unresolve_one(p);
@@ -670,10 +669,6 @@ static int do_unresolve(int ac, const char **av,
 static int do_reupdate(const char **paths,
 		       const char *prefix)
 {
-	/* Read HEAD and run update-index on paths that are
-	 * merged and already different between index and HEAD.
-	 */
-	int pos;
 	int has_head = 1;
 	struct pathspec pathspec;
 	struct object_id head_oid;
@@ -688,7 +683,7 @@ static int do_reupdate(const char **paths,
 		 */
 		has_head = 0;
  redo:
-	for (pos = 0; pos < the_index.cache_nr; pos++) {
+	for (int pos = 0; pos < the_index.cache_nr; pos++) {
 		const struct cache_entry *ce = the_index.cache[pos];
 		struct cache_entry *old = NULL;
 		int save_nr;
diff --git a/builtin/var.c b/builtin/var.c
index cf5567208a..3aa4e4d45b 100644
--- a/builtin/var.c
+++ b/builtin/var.c
@@ -168,10 +168,9 @@ static struct git_var git_vars[] = {
 
 static void list_vars(void)
 {
-	struct git_var *ptr;
 	char *val;
 
-	for (ptr = git_vars; ptr->read; ptr++)
+	for (struct git_var *ptr = git_vars; ptr->read; ptr++)
 		if ((val = ptr->read(0))) {
 			if (ptr->multivalued && *val) {
 				struct string_list list = STRING_LIST_INIT_DUP;
@@ -190,8 +189,7 @@ static void list_vars(void)
 
 static const struct git_var *get_git_var(const char *var)
 {
-	struct git_var *ptr;
-	for (ptr = git_vars; ptr->read; ptr++) {
+	for (struct git_var *ptr = git_vars; ptr->read; ptr++) {
 		if (strcmp(var, ptr->name) == 0) {
 			return ptr;
 		}
diff --git a/builtin/verify-pack.c b/builtin/verify-pack.c
index 011dddd2dc..a342d5adf3 100644
--- a/builtin/verify-pack.c
+++ b/builtin/verify-pack.c
@@ -66,7 +66,6 @@ int cmd_verify_pack(int argc, const char **argv, const char *prefix)
 	int err = 0;
 	unsigned int flags = 0;
 	const char *object_format = NULL;
-	int i;
 	const struct option verify_pack_options[] = {
 		OPT_BIT('v', "verbose", &flags, N_("verbose"),
 			VERIFY_PACK_VERBOSE),
@@ -82,7 +81,7 @@ int cmd_verify_pack(int argc, const char **argv, const char *prefix)
 			     verify_pack_usage, 0);
 	if (argc < 1)
 		usage_with_options(verify_pack_usage, verify_pack_options);
-	for (i = 0; i < argc; i++) {
+	for (int i = 0; i < argc; i++) {
 		if (verify_one_pack(argv[i], flags, object_format))
 			err = 1;
 	}
diff --git a/builtin/worktree.c b/builtin/worktree.c
index 9c76b62b02..d4c5b6b7d3 100644
--- a/builtin/worktree.c
+++ b/builtin/worktree.c
@@ -191,10 +191,8 @@ static int prune_cmp(const void *a, const void *b)
 
 static void prune_dups(struct string_list *l)
 {
-	int i;
-
 	QSORT(l->items, l->nr, prune_cmp);
-	for (i = 1; i < l->nr; i++) {
+	for (int i = 1; i < l->nr; i++) {
 		if (!fspathcmp(l->items[i].string, l->items[i - 1].string))
 			prune_worktree(l->items[i].util, "duplicate entry");
 	}
@@ -999,9 +997,7 @@ static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
 
 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
 {
-	int i;
-
-	for (i = 0; wt[i]; i++) {
+	for (int i = 0; wt[i]; i++) {
 		int sha1_len;
 		int path_len = strlen(wt[i]->path);
 
@@ -1055,7 +1051,7 @@ static int list(int ac, const char **av, const char *prefix)
 		die(_("the option '%s' requires '%s'"), "-z", "--porcelain");
 	else {
 		struct worktree **worktrees = get_worktrees();
-		int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
+		int path_maxlen = 0, abbrev = DEFAULT_ABBREV;
 
 		/* sort worktrees by path but keep main worktree at top */
 		pathsort(worktrees + 1);
@@ -1063,7 +1059,7 @@ static int list(int ac, const char **av, const char *prefix)
 		if (!porcelain)
 			measure_widths(worktrees, &abbrev, &path_maxlen);
 
-		for (i = 0; worktrees[i]; i++) {
+		for (int i = 0; worktrees[i]; i++) {
 			if (porcelain)
 				show_worktree_porcelain(worktrees[i],
 							line_terminator);
diff --git a/bulk-checkin.c b/bulk-checkin.c
index eb46b88637..c00c4ad3a7 100644
--- a/bulk-checkin.c
+++ b/bulk-checkin.c
@@ -51,7 +51,6 @@ static void flush_bulk_checkin_packfile(struct bulk_checkin_packfile *state)
 {
 	unsigned char hash[GIT_MAX_RAWSZ];
 	struct strbuf packname = STRBUF_INIT;
-	int i;
 
 	if (!state->f)
 		return;
@@ -76,7 +75,7 @@ static void flush_bulk_checkin_packfile(struct bulk_checkin_packfile *state)
 	finish_tmp_packfile(&packname, state->pack_tmp_name,
 			    state->written, state->nr_written,
 			    &state->pack_idx_opts, hash);
-	for (i = 0; i < state->nr_written; i++)
+	for (int i = 0; i < state->nr_written; i++)
 		free(state->written[i]);
 
 clear_exit:
@@ -124,14 +123,12 @@ static void flush_batch_fsync(void)
 
 static int already_written(struct bulk_checkin_packfile *state, struct object_id *oid)
 {
-	int i;
-
 	/* The object may already exist in the repository */
 	if (repo_has_object_file(the_repository, oid))
 		return 1;
 
 	/* Might want to keep the list sorted */
-	for (i = 0; i < state->nr_written; i++)
+	for (int i = 0; i < state->nr_written; i++)
 		if (oideq(&state->written[i]->oid, oid))
 			return 1;
 
diff --git a/bundle-uri.c b/bundle-uri.c
index ca32050a78..45d615a3db 100644
--- a/bundle-uri.c
+++ b/bundle-uri.c
@@ -114,8 +114,7 @@ void print_bundle_list(FILE *fp, struct bundle_list *list)
 	fprintf(fp, "\tmode = %s\n", mode);
 
 	if (list->heuristic) {
-		int i;
-		for (i = 0; i < BUNDLE_HEURISTIC__COUNT; i++) {
+		for (int i = 0; i < BUNDLE_HEURISTIC__COUNT; i++) {
 			if (heuristics[i].heuristic == list->heuristic) {
 				printf("\theuristic = %s\n",
 				       heuristics[list->heuristic].name);
@@ -167,8 +166,7 @@ static int bundle_list_update(const char *key, const char *value,
 		}
 
 		if (!strcmp(subkey, "heuristic")) {
-			int i;
-			for (i = 0; i < BUNDLE_HEURISTIC__COUNT; i++) {
+			for (int i = 0; i < BUNDLE_HEURISTIC__COUNT; i++) {
 				if (heuristics[i].heuristic &&
 				    heuristics[i].name &&
 				    !strcmp(value, heuristics[i].name)) {
diff --git a/bundle.c b/bundle.c
index a9744da255..419ba4cc45 100644
--- a/bundle.c
+++ b/bundle.c
@@ -60,9 +60,7 @@ static int parse_capability(struct bundle_header *header, const char *capability
 
 static int parse_bundle_signature(struct bundle_header *header, const char *line)
 {
-	int i;
-
-	for (i = 0; i < ARRAY_SIZE(bundle_sigs); i++) {
+	for (int i = 0; i < ARRAY_SIZE(bundle_sigs); i++) {
 		if (!strcmp(line, bundle_sigs[i].signature)) {
 			header->version = bundle_sigs[i].version;
 			return 0;
@@ -167,9 +165,7 @@ int is_bundle(const char *path, int quiet)
 
 static int list_refs(struct string_list *r, int argc, const char **argv)
 {
-	int i;
-
-	for (i = 0; i < r->nr; i++) {
+	for (int i = 0; i < r->nr; i++) {
 		struct object_id *oid;
 		const char *name;
 
@@ -216,7 +212,7 @@ int verify_bundle(struct repository *r,
 	 * to be verbose about the errors
 	 */
 	struct string_list *p = &header->prerequisites;
-	int i, ret = 0;
+	int ret = 0;
 	const char *message = _("Repository lacks these prerequisite commits:");
 	struct string_list_iterator iter = {
 		.list = p,
@@ -228,7 +224,7 @@ int verify_bundle(struct repository *r,
 	if (!r || !r->objects || !r->objects->odb)
 		return error(_("need a repository to verify a bundle"));
 
-	for (i = 0; i < p->nr; i++) {
+	for (int i = 0; i < p->nr; i++) {
 		struct string_list_item *e = p->items + i;
 		const char *name = e->string;
 		struct object_id *oid = e->util;
@@ -320,7 +316,6 @@ static int is_tag_in_date_range(struct object *tag, struct rev_info *revs)
 static int write_pack_data(int bundle_fd, struct rev_info *revs, struct strvec *pack_options)
 {
 	struct child_process pack_objects = CHILD_PROCESS_INIT;
-	int i;
 
 	strvec_pushl(&pack_objects.args,
 		     "pack-objects",
@@ -350,7 +345,7 @@ static int write_pack_data(int bundle_fd, struct rev_info *revs, struct strvec *
 	if (start_command(&pack_objects))
 		return error(_("Could not spawn pack-objects"));
 
-	for (i = 0; i < revs->pending.nr; i++) {
+	for (int i = 0; i < revs->pending.nr; i++) {
 		struct object *object = revs->pending.objects[i].item;
 		if (object->flags & UNINTERESTING)
 			write_or_die(pack_objects.in, "^", 1);
@@ -374,10 +369,9 @@ static int write_pack_data(int bundle_fd, struct rev_info *revs, struct strvec *
  */
 static int write_bundle_refs(int bundle_fd, struct rev_info *revs)
 {
-	int i;
 	int ref_count = 0;
 
-	for (i = 0; i < revs->pending.nr; i++) {
+	for (int i = 0; i < revs->pending.nr; i++) {
 		struct object_array_entry *e = revs->pending.objects + i;
 		struct object_id oid;
 		char *ref;
@@ -500,7 +494,6 @@ int create_bundle(struct repository *r, const char *path,
 	struct rev_info revs, revs_copy;
 	int min_version = 2;
 	struct bundle_prerequisites_info bpi;
-	int i;
 
 	/* init revs to list objects for pack-objects later */
 	save_commit_buffer = 0;
@@ -566,7 +559,7 @@ int create_bundle(struct repository *r, const char *path,
 	revs_copy.pending.nr = 0;
 	revs_copy.pending.alloc = 0;
 	revs_copy.pending.objects = NULL;
-	for (i = 0; i < revs.pending.nr; i++) {
+	for (int i = 0; i < revs.pending.nr; i++) {
 		struct object_array_entry *e = revs.pending.objects + i;
 		if (e)
 			add_object_array_with_path(e->item, e->name,
diff --git a/cache-tree.c b/cache-tree.c
index 64678fe199..1aa30bdd80 100644
--- a/cache-tree.c
+++ b/cache-tree.c
@@ -27,12 +27,11 @@ struct cache_tree *cache_tree(void)
 
 void cache_tree_free(struct cache_tree **it_p)
 {
-	int i;
 	struct cache_tree *it = *it_p;
 
 	if (!it)
 		return;
-	for (i = 0; i < it->subtree_nr; i++)
+	for (int i = 0; i < it->subtree_nr; i++)
 		if (it->down[i]) {
 			cache_tree_free(&it->down[i]->cache_tree);
 			free(it->down[i]);
@@ -216,8 +215,8 @@ static void discard_unused_subtrees(struct cache_tree *it)
 {
 	struct cache_tree_sub **down = it->down;
 	int nr = it->subtree_nr;
-	int dst, src;
-	for (dst = src = 0; src < nr; src++) {
+	int src;
+	for (int dst = src = 0; src < nr; src++) {
 		struct cache_tree_sub *s = down[src];
 		if (s->used)
 			down[dst++] = s;
@@ -231,12 +230,11 @@ static void discard_unused_subtrees(struct cache_tree *it)
 
 int cache_tree_fully_valid(struct cache_tree *it)
 {
-	int i;
 	if (!it)
 		return 0;
 	if (it->entry_count < 0 || !repo_has_object_file(the_repository, &it->oid))
 		return 0;
-	for (i = 0; i < it->subtree_nr; i++) {
+	for (int i = 0; i < it->subtree_nr; i++) {
 		if (!cache_tree_fully_valid(it->down[i]->cache_tree))
 			return 0;
 	}
@@ -495,8 +493,6 @@ int cache_tree_update(struct index_state *is
Junio C Hamano· Feb 15, 2024, 17:33 UTC · re: Elia Pinto · lore

Re: [PATCH] use C99 declaration of variable in for() loop

Elia Pinto <gitter.spiros@gmail.com> writes:
Show 5 quoted lines
> With the exception of cbtree.c, which would need initial
> reworking to remove the usage of goto, it expands the
> use of variable scope reduction in for loops as
> permitted by the C99 standard, which was first introduced
> in the git codebase with commit 44ba10d6.
Thanks, but ...

Our test balloon may have proven that nobody will be inconvenienced, and it does mean we can be liberal using it when we add new code or update existing loops "while at it", but I personally do not think such a code churn is very welcome.

Christian Couder· Feb 15, 2024, 18:17 UTC · re: Junio C Hamano · lore

Re: [PATCH] use C99 declaration of variable in for() loop

On Thu, Feb 15, 2024 at 6:33 PM Junio C Hamano <gitster@pobox.com> wrote:
Show 15 quoted lines
>
> Elia Pinto <gitter.spiros@gmail.com> writes:
>
> > With the exception of cbtree.c, which would need initial
> > reworking to remove the usage of goto, it expands the
> > use of variable scope reduction in for loops as
> > permitted by the C99 standard, which was first introduced
> > in the git codebase with commit 44ba10d6.
>
> Thanks, but ...
>
> Our test balloon may have proven that nobody will be inconvenienced,
> and it does mean we can be liberal using it when we add new code or
> update existing loops "while at it", but I personally do not think
> such a code churn is very welcome.

Perhaps such changes could be accepted when they are made in only one file as part of a microproject though?

Junio C Hamano· Feb 15, 2024, 18:49 UTC · re: Christian Couder · lore

Re: [PATCH] use C99 declaration of variable in for() loop

Christian Couder <christian.couder@gmail.com> writes:
> Perhaps such changes could be accepted when they are made in only one
> file as part of a microproject though?

Yes, a microproject is not about helping this project, but is about us investing our cycles in helping aspiring developers with small practice material. Even though we may not want to see massive code churn, we can view the cost of reviewing and accepting small changes as a part of the cost to onboard new folks.

Elia Pinto· Feb 15, 2024, 18:56 UTC · re: Junio C Hamano · lore

Re: [PATCH] use C99 declaration of variable in for() loop

Il giorno gio 15 feb 2024 alle ore 18:33 Junio C Hamano <gitster@pobox.com> ha scritto:

Show 15 quoted lines
>
> Elia Pinto <gitter.spiros@gmail.com> writes:
>
> > With the exception of cbtree.c, which would need initial
> > reworking to remove the usage of goto, it expands the
> > use of variable scope reduction in for loops as
> > permitted by the C99 standard, which was first introduced
> > in the git codebase with commit 44ba10d6.
>
> Thanks, but ...
>
> Our test balloon may have proven that nobody will be inconvenienced,
> and it does mean we can be liberal using it when we add new code or
> update existing loops "while at it", but I personally do not think
> such a code churn is very welcome.

Thank you for your reply. I can understand that, clearly. However, this means that extensive code refactoring contributions are never welcome. I am not saying this is a problem, but just an observation.

Best
Junio C Hamano· Feb 15, 2024, 20:07 UTC · re: Elia Pinto · lore

Re: [PATCH] use C99 declaration of variable in for() loop

Elia Pinto <gitter.spiros@gmail.com> writes:
> Thank you for your reply. I can understand that, clearly. However,
> this means that extensive code
> refactoring contributions are never welcome. I am not saying this is a
> problem, but just an observation.

Such changes can happen and have happened when the benefit of such code churn outweighs the cost of reviewing *and* cost of updating or adjusting in-flight topics that may already or may not yet be in my tree. Coccinelle-driven patches that can be mechanically reproduced and whose validity can be trusted can be one way to reduce the review and maintenance cost for such a tree-wide change.

brian m. carlson· Feb 15, 2024, 23:12 UTC · re: Junio C Hamano · lore

Re: [PATCH] use C99 declaration of variable in for() loop

On 2024-02-15 at 17:33:22, Junio C Hamano wrote:
Show 14 quoted lines
> Elia Pinto <gitter.spiros@gmail.com> writes:
> 
> > With the exception of cbtree.c, which would need initial
> > reworking to remove the usage of goto, it expands the
> > use of variable scope reduction in for loops as
> > permitted by the C99 standard, which was first introduced
> > in the git codebase with commit 44ba10d6.
> 
> Thanks, but ...
> 
> Our test balloon may have proven that nobody will be inconvenienced,
> and it does mean we can be liberal using it when we add new code or
> update existing loops "while at it", but I personally do not think
> such a code churn is very welcome.

I will also say that sending one giant patch for this may be a bit hard to review. While I will defer to Junio's opinion as the maintainer, I would be more inclined to review this kind of series if it came in in smaller patches, a few at a time, in which case I would find it a welcome improvement.

Since my time to work on Git is relatively limited, having, say, a five-patch series where we each update a single file would let me review these changes in a relatively short amount of time, which I would be more likely to be able to find time for. Looking at the large patch, I'd be worried that I wouldn't be able to get through the entire thing in one sitting.

Of course, if you bring in a nice Coccinelle patch for it, then that may make a longer (but still one-file-per-commit) series more viable, since it will help reviewers have more confidence in your change.

-- 
brian m. carlson (he/him or they/them)
Toronto, Ontario, CA
Junio C Hamano· Feb 15, 2024, 23:43 UTC · re: brian m. carlson · lore

Re: [PATCH] use C99 declaration of variable in for() loop

"brian m. carlson" <sandals@crustytoothpaste.net> writes:
Show 5 quoted lines
> I will also say that sending one giant patch for this may be a bit hard
> to review.  While I will defer to Junio's opinion as the maintainer, I
> would be more inclined to review this kind of series if it came in in
> smaller patches, a few at a time, in which case I would find it a
> welcome improvement.

True. As to the specific topic of using "for (int i = 0; ...)", it is tedious to review for mistakes and 17000+ lines of patch is not a way to do so. I do not think I would be able to spot a change in behaviour caused by a hunk like this

	int i = 3;
	... after some operations ...
-	for (i = 0; i < 5; i++)
+	for (int i = 0; i < 5; i++)
		if (condition_on_i(i))
			break;
	... after some operations ...
	return i;

after scanning similar changes for 1000+ times in a single huge patch.

← back to recent threads